forked from Prinzhorn/skrollr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
skrollr.js
648 lines (523 loc) · 16 KB
/
skrollr.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
/*! skrollr v0.3.3 https://github.com/Prinzhorn/skrollr | free to use under terms of MIT license */
(function(window, document, undefined) {
//Used as a dummy function for event listeners.
var noop = function() {};
//Minify optimization.
var hasProp = Object.prototype.hasOwnProperty;
var documentElement = document.documentElement;
var body = document.body;
var HIDDEN_CLASS = 'hidden';
var SKROLLABLE_CLASS = 'skrollable';
var DEFAULT_EASING = 'linear';
var requestAnimFrame =
window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(fn) {
//Just 30 fps, because that's enough for those legacy browsers
setTimeout(fn, 1000 / 30);
};
var rxTrim = /^\s*(.*)\s$/;
//Find data-<number>, as well as data-end and data-end-<number>
var rxKeyframeAttribute = /^data(-end)?-?(\d+)?$/;
var rxPropSplit = /:|;/g;
//Easing function names follow the property in square brackets.
var rxPropEasing = /^([a-z-]+)\[(\w+)\]$/;
var rxCamelCase = /-([a-z])/g;
//Numeric values with optional sign.
var rxNumericValue = /(:?\+|-)?[\d.]+/g;
//Finds rgb(a) colors, which don't use the percentage notation.
var rxRGBAIntegerColor = /rgba?\(\s*-?\d+\s*,\s*-?\d+\s*,\s*-?\d+/g;
//Finds all gradients.
var rxGradient = /[a-z-]+-gradient/g;
//Only relevant prefixes. May be extended.
//Could be dangerous if there will ever be a CSS property which actually starts with "ms". Don't hope so.
var rxPrefixes = /^O|Moz|webkit|ms/;
var theCSSPrefix;
var theDashedCSSPrefix;
//Detect prefix for current browser by finding the first property using a prefix.
for(var k in body.style) {
//Yes, this is meant to be an assignment.
if(theCSSPrefix = k.match(rxPrefixes)) {
break;
}
}
//Empty string if no prefix detected
theCSSPrefix = (theCSSPrefix || [''])[0];
//Will be "--" if no prefix detected. No problem, browser will ignore "--transform" and stuff.
theDashedCSSPrefix = '-' + theCSSPrefix.toLowerCase() + '-';
//Cleanup.
rxPrefixes = undefined;
//Built-in easing functions.
var easings = {
begin: function() {
return 0;
},
end: function() {
return 1;
},
linear: function(p) {
return p;
},
quadratic: function(p) {
return p * p;
},
cubic: function(p) {
return p * p * p * p;
},
swing: function(p) {
return (-Math.cos(p * Math.PI) / 2) + .5;
},
//see https://www.desmos.com/calculator/tbr20s8vd2 for how I did this
bounce: function(p) {
var a;
switch(true) {
case (p <= .5083):
a = 3; break;
case (p <= .8489):
a = 9; break;
case (p <= .96208):
a = 27; break;
case (p <= .99981):
a = 91; break;
default:
return 1;
}
return 1 - Math.abs(3 * Math.cos(p * a * 1.028) / a);
}
};
//Will contain all plugin-functions.
var plugins = {};
/**
* Constructor.
*/
function Skrollr(options) {
var self = this;
options = options || {};
//We allow defining custom easings or overwrite existing
if(options.easing) {
for(var e in options.easing) {
easings[e] = options.easing[e];
}
}
//Scale factor to scale key frames.
self.scale = options.scale || 1;
self.listeners = {
//Function to be called right before rendering.
beforerender: options.beforerender || noop,
//Function to be called right after finishing rendering.
render: options.render || noop
};
/*
A list of all elements which should be animated associated with their the metadata.
Exmaple skrollable with two key frames animating from 100px width to 20px:
skrollable = {
element: <the DOM element>,
keyFrames: [
{
frame: 100,
props: {
width: {
value: ['?px', 100],
easing: <reference to easing function>
}
}
},
{
frame: 200,
props: {
width: {
value: ['?px', 20],
easing: <reference to easing function>
}
}
}
]
};
*/
self.skrollables = [];
//Will contain the max key frame value available.
self.maxKeyFrame = options.maxKeyFrame || 0;
//Current direction (up/down).
self.dir = 'down';
//The last top offset value. Needed to determine direction.
self.lastTop = -1;
//The current top offset, needed for async rendering.
self.curTop = 0;
var allElements = document.getElementsByTagName('*');
//Will contain references to all "data-end" key frames.
var atEndKeyFrames = [];
//Iterate over all elements in document.
for(var i = 0; i < allElements.length; i++) {
var el = allElements[i];
var keyFrames = [];
if(!el.attributes) {
continue;
}
//Iterate over all attributes and search for key frame attributes.
for (var k = 0; k < el.attributes.length; k++) {
var attr = el.attributes[k];
var match = attr.name.match(rxKeyframeAttribute);
if(match !== null) {
var frame;
var kf;
frame = (match[2] | 0) * self.scale;
kf = {
frame: frame,
props: attr.value
};
keyFrames.push(kf);
//special handling for data-end
if(match[1] === '-end') {
atEndKeyFrames.push(kf);
}
if(frame > self.maxKeyFrame) {
self.maxKeyFrame = frame;
}
}
}
//Does this element have key frames?
if(keyFrames.length) {
self.skrollables.push({
element: el,
keyFrames: keyFrames
});
addClass(el, SKROLLABLE_CLASS);
}
}
//Set all data-end key frames to max key frame
for(var i = 0; i < atEndKeyFrames.length; i++) {
var kf = atEndKeyFrames[i];
kf.frame = self.maxKeyFrame - kf.frame;
}
//Now that we got all key frame numbers right, actually parse the properties.
for(var i = 0; i < self.skrollables.length; i++) {
var sk = self.skrollables[i];
//Make sure they are in order
sk.keyFrames.sort(function(a, b) {
return a.frame - b.frame;
});
//Parse the property string to objects
self._parseProps(sk);
//Fill key frames with missing properties from left and right
self._fillProps(sk);
}
//Add a dummy element in order to get a large enough scrollbar
var dummy = document.createElement('div');
var dummyStyle = dummy.style;
dummyStyle.width = '1px';
dummyStyle.position = 'absolute';
dummyStyle.right = dummyStyle.top = dummyStyle.zIndex = '0';
body.appendChild(dummy);
//Update height of dummy div when window size is changed.
var onResize = function() {
dummyStyle.height = (self.maxKeyFrame + documentElement.clientHeight) + 'px';
};
if(window.addEventListener) {
window.addEventListener('resize', onResize, false);
} else {
window.attachEvent('onresize', onResize);
}
onResize();
//Let's go
self._render();
//Clean up
dummy = atEndKeyFrames = options = undefined;
return self;
}
Skrollr.prototype.setScrollTop = function(top) {
pageYOffset = body.scrollTop = documentElement.scrollTop = top;
};
Skrollr.prototype.on = function(name, fn) {
this.listeners[name] = fn || noop;
};
Skrollr.prototype.off = function(name) {
this.listeners[name] = noop;
};
/**
* Calculate and sets the style properties for the element at the given frame
*/
Skrollr.prototype._calcSteps = function(skrollable, frame) {
var self = this;
var frames = skrollable.keyFrames;
//We are before the first frame, don't do anything
if(frame < frames[0].frame) {
addClass(skrollable.element, HIDDEN_CLASS);
}
//We are after the last frame, the element gets all props from last key frame
else if(frame > frames[frames.length - 1].frame) {
removeClass(skrollable.element, HIDDEN_CLASS);
var last = frames[frames.length - 1];
var value;
for(var key in last.props) {
if(hasProp.call(last.props, key)) {
value = self._interpolateString(last.props[key].value);
self._setStyle(skrollable.element, key, value);
}
}
}
//We are between two frames
else {
removeClass(skrollable.element, HIDDEN_CLASS);
//Find out between which two key frames we are right now
for(var i = 0; i < frames.length - 1; i++) {
if(frame >= frames[i].frame && frame <= frames[i + 1].frame) {
var left = frames[i];
var right = frames[i + 1];
for(var key in left.props) {
if(hasProp.call(left.props, key)) {
var progress = (frame - left.frame) / (right.frame - left.frame);
//Transform the current progress using the given easing function.
progress = left.props[key].easing(progress);
//Interpolate between the two values
var value = self._calcInterpolation(left.props[key].value, right.props[key].value, progress);
value = self._interpolateString(value);
self._setStyle(skrollable.element, key, value);
}
}
break;
}
}
}
};
/**
* Renders all elements
*/
Skrollr.prototype._render = function() {
var self = this;
self.curTop = window.pageYOffset || documentElement.scrollTop || body.scrollTop || 0;
//In OSX it's possible to have a negative scrolltop, so, we set it to zero.
if(self.curTop < 0) {
self.curTop = 0;
}
//Did the scroll position even change?
if(self.lastTop !== self.curTop) {
//Remember in which direction are we scrolling?
self.dir = (self.curTop >= self.lastTop) ? 'down' : 'up';
var listenerParams = {
curTop: self.curTop,
lastTop: self.lastTop,
maxTop: self.maxKeyFrame,
direction: self.dir
};
//Tell the listener we are about to render.
var continueRendering = self.listeners.beforerender.call(self, listenerParams);
//The beforerender listener function is able the cancel rendering.
if(continueRendering !== false) {
for(var i = 0; i < self.skrollables.length; i++) {
self._calcSteps(self.skrollables[i], self.curTop);
}
//Remember when we last rendered.
self.lastTop = self.curTop;
self.listeners.render.call(self, listenerParams);
}
}
requestAnimFrame(function() {
self._render();
});
};
/**
* Parses the properties for each key frame of the given skrollable.
*/
Skrollr.prototype._parseProps = function(skrollable) {
var self = this;
//Iterate over all key frames
for(var i = 0; i < skrollable.keyFrames.length; i++) {
var frame = skrollable.keyFrames[i];
//Get all properties and values in an array
var allProps = frame.props.split(rxPropSplit);
var prop;
var value;
var easing;
frame.props = {};
//Iterate over all props and values (+2 because [prop,value,prop,value,...])
for(var k = 0; k < allProps.length - 1; k += 2) {
prop = allProps[k];
value = allProps[k + 1];
easing = prop.match(rxPropEasing);
//Is there an easing specified for this prop?
if(easing !== null) {
prop = easing[1];
easing = easing[2];
} else {
easing = DEFAULT_EASING;
}
value = self._parseProp(value);
//Save the prop for this key frame with his value and easing function
frame.props[prop] = {
value: value,
easing: easings[easing]
};
}
}
};
/**
* Parses a value extracting numeric values and generating a format string
* for later interpolation of the new values in old string.
*
* @param val The CSS value to be parsed.
* @return Something like ["rgba(?%,?%, ?%,?)", 100, 50, 0, .7]
* where the first element is the format string later used
* and all following elements are the numeric value.
*/
Skrollr.prototype._parseProp = function(val) {
var numbers = [];
//One special case, where floats don't work.
//We replace all occurences of rgba colors
//which don't use percentage notation with the percentage notation.
rxRGBAIntegerColor.lastIndex = 0;
val = val.replace(rxRGBAIntegerColor, function(rgba) {
return rgba.replace(rxNumericValue, function(n) {
return n / 255 * 100 + '%';
});
});
//Handle prefixing of "gradient" values.
//For now only the prefixed value will be set. Unprefixed isn't supported anyway.
rxGradient.lastIndex = 0;
val = val.replace(rxGradient, function(s) {
return theDashedCSSPrefix + s;
});
//Now parse ANY number inside this string and create a format string.
val = val.replace(rxNumericValue, function(n) {
numbers.push(+n);
return '?';
});
//Add the formatstring as first value.
numbers.unshift(val);
return numbers;
};
/**
* Fills the key frames with missing left and right hand properties.
* If key frame 1 has property X and key frame 2 is missing X,
* but key frame 3 has X again, then we need to assign X to key frame 2 too.
*
* @param sk A skrollable.
*/
Skrollr.prototype._fillProps = function(sk) {
//Will collect the properties key frame by key frame
var propList = {};
var self = this;
//Iterate over all key frames from left to right
for(var i = 0; i < sk.keyFrames.length; i++) {
self._fillPropForFrame(sk.keyFrames[i], propList);
}
//Now do the same from right to fill the last gaps
propList = {};
//Iterate over all key frames from right to left
for(var i = sk.keyFrames.length - 1; i >= 0; i--) {
self._fillPropForFrame(sk.keyFrames[i], propList);
}
};
Skrollr.prototype._fillPropForFrame = function(frame, propList) {
//For each key frame iterate over all right hand properties and assign them,
//but only if the current key frame doesn't have the property by itself
for(var key in propList) {
//The current frame misses this property, so assign it.
if(!hasProp.call(frame.props, key)) {
frame.props[key] = propList[key];
}
}
//Iterate over all props of the current frame and collect them
for(var key in frame.props) {
propList[key] = frame.props[key];
}
};
/**
* Calculates the new values for two given values array.
*/
Skrollr.prototype._calcInterpolation = function(val1, val2, progress) {
//They both need to have the same length
if(val1.length !== val2.length) {
throw 'Can\'t interpolate between "' + val1[0] + '" and "' + val2[0] + '"';
}
//Add the format string as first element.
var interpolated = [val1[0]];
for(var i = 1; i < val1.length; i++) {
//That's the line where the two numbers are actually interpolated.
interpolated[i] = val1[i] + ((val2[i] - val1[i]) * progress);
}
return interpolated;
};
/**
* Interpolates the numeric values into the format string.
*/
Skrollr.prototype._interpolateString = function(val) {
var i = 1;
return val[0].replace(/\?/g, function() {
return val[i++];
});
};
/**
* Set the CSS property on the given element. Sets prefixed properties as well.
*/
Skrollr.prototype._setStyle = function(el, prop, val) {
var style = el.style;
//Camel case.
prop = prop.replace(rxCamelCase, function(str, p1) {
return p1.toUpperCase();
}).replace('-', '');
//Make sure z-index gets a <integer>.
//This is the only <integer> case we need to handle.
if(prop === 'zIndex') {
//Floor
style[prop] = '' + (val | 0);
}
else {
//Need try-catch for old IE.
try {
//Set prefixed property.
style[theCSSPrefix + prop.slice(0,1).toUpperCase() + prop.slice(1)] = val;
//Set unprefixed.
style[prop] = val;
} catch(ignore) {}
}
//Plugin entry point.
if(plugins.setStyle) {
for(var i = 0; i < plugins.setStyle.length; i++) {
plugins.setStyle[0].call(this, el, prop, val);
}
}
};
/*
Helpers which don't necessarily belong to the skrollr Object.
*/
/**
* Adds a CSS class.
*/
var addClass = function(el, name) {
if(untrim(el.className).indexOf(untrim(name)) === -1) {
el.className = (el.className + ' ' + name).replace(rxTrim, '$1');
}
};
/**
* Removes a CSS class.
*/
var removeClass = function(el, name) {
el.className = (untrim(el.className)).replace(untrim(name), '').replace(rxTrim, '$1');
};
/**
* Adds a space before and after the string.
*/
var untrim = function(a) {
return ' ' + a + ' ';
};
//Global api.
window.skrollr = {
//Main entry point.
init: function(options) {
return new Skrollr(options);
},
//Plugin api.
plugin: function(entryPoint, fn) {
//Each entry point may contain multiple plugin-functions.
if(plugins[entryPoint]) {
plugins[entryPoint].push(fn);
} else {
plugins[entryPoint] = [fn];
}
},
VERSION: '0.3.3'
};
}(window, document));