-
Notifications
You must be signed in to change notification settings - Fork 0
/
skrollr.js
1780 lines (1415 loc) · 47.3 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
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*!
* skrollr core
*
* Alexander Prinzhorn - https://github.com/Prinzhorn/skrollr
*
* Free to use under terms of MIT license
*/
(function(window, document, undefined) {
'use strict';
/*
* Global api.
*/
var skrollr = {
get: function() {
return _instance;
},
//Main entry point.
init: function(options) {
return _instance || new Skrollr(options);
},
VERSION: '0.6.30'
};
//Minify optimization.
var hasProp = Object.prototype.hasOwnProperty;
var Math = window.Math;
var getStyle = window.getComputedStyle;
//They will be filled when skrollr gets initialized.
var documentElement;
var body;
var EVENT_TOUCHSTART = 'touchstart';
var EVENT_TOUCHMOVE = 'touchmove';
var EVENT_TOUCHCANCEL = 'touchcancel';
var EVENT_TOUCHEND = 'touchend';
var SKROLLABLE_CLASS = 'skrollable';
var SKROLLABLE_BEFORE_CLASS = SKROLLABLE_CLASS + '-before';
var SKROLLABLE_BETWEEN_CLASS = SKROLLABLE_CLASS + '-between';
var SKROLLABLE_AFTER_CLASS = SKROLLABLE_CLASS + '-after';
var SKROLLR_CLASS = 'skrollr';
var NO_SKROLLR_CLASS = 'no-' + SKROLLR_CLASS;
var SKROLLR_DESKTOP_CLASS = SKROLLR_CLASS + '-desktop';
var SKROLLR_MOBILE_CLASS = SKROLLR_CLASS + '-mobile';
var DEFAULT_EASING = 'linear';
var DEFAULT_DURATION = 1000;//ms
var DEFAULT_MOBILE_DECELERATION = 0.004;//pixel/ms²
var DEFAULT_SKROLLRBODY = 'skrollr-body';
var DEFAULT_SMOOTH_SCROLLING_DURATION = 200;//ms
var ANCHOR_START = 'start';
var ANCHOR_END = 'end';
var ANCHOR_CENTER = 'center';
var ANCHOR_BOTTOM = 'bottom';
//The property which will be added to the DOM element to hold the ID of the skrollable.
var SKROLLABLE_ID_DOM_PROPERTY = '___skrollable_id';
var rxTouchIgnoreTags = /^(?:input|textarea|button|select)$/i;
var rxTrim = /^\s+|\s+$/g;
//Find all data-attributes. data-[_constant]-[offset]-[anchor]-[anchor].
var rxKeyframeAttribute = /^data(?:-(_\w+))?(?:-?(-?\d*\.?\d+p?))?(?:-?(start|end|top|center|bottom))?(?:-?(top|center|bottom))?$/;
var rxPropValue = /\s*(@?[\w\-\[\]]+)\s*:\s*(.+?)\s*(?:;|$)/gi;
//Easing function names follow the property in square brackets.
var rxPropEasing = /^(@?[a-z\-]+)\[(\w+)\]$/;
var rxCamelCase = /-([a-z0-9_])/g;
var rxCamelCaseFn = function(str, letter) {
return letter.toUpperCase();
};
//Numeric values with optional sign.
var rxNumericValue = /[\-+]?[\d]*\.?[\d]+/g;
//Used to replace occurences of {?} with a number.
var rxInterpolateString = /\{\?\}/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;
//Vendor prefix. Will be set once skrollr gets initialized.
var theCSSPrefix = '';
var theDashedCSSPrefix = '';
//Will be called once (when skrollr gets initialized).
var detectCSSPrefix = function() {
//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)|(?:-(?:o|moz|webkit|ms)-)/;
//Detect prefix for current browser by finding the first property using a prefix.
if(!getStyle) {
return;
}
var style = getStyle(body, null);
for(var k in style) {
//We check the key and if the key is a number, we check the value as well, because safari's getComputedStyle returns some weird array-like thingy.
theCSSPrefix = (k.match(rxPrefixes) || (+k == k && style[k].match(rxPrefixes)));
if(theCSSPrefix) {
break;
}
}
//Did we even detect a prefix?
if(!theCSSPrefix) {
theCSSPrefix = theDashedCSSPrefix = '';
return;
}
theCSSPrefix = theCSSPrefix[0];
//We could have detected either a dashed prefix or this camelCaseish-inconsistent stuff.
if(theCSSPrefix.slice(0,1) === '-') {
theDashedCSSPrefix = theCSSPrefix;
//There's no logic behind these. Need a look up.
theCSSPrefix = ({
'-webkit-': 'webkit',
'-moz-': 'Moz',
'-ms-': 'ms',
'-o-': 'O'
})[theCSSPrefix];
} else {
theDashedCSSPrefix = '-' + theCSSPrefix.toLowerCase() + '-';
}
};
var polyfillRAF = function() {
var requestAnimFrame = window.requestAnimationFrame || window[theCSSPrefix.toLowerCase() + 'RequestAnimationFrame'];
var lastTime = _now();
if(_isMobile || !requestAnimFrame) {
requestAnimFrame = function(callback) {
//How long did it take to render?
var deltaTime = _now() - lastTime;
var delay = Math.max(0, 1000 / 60 - deltaTime);
return window.setTimeout(function() {
lastTime = _now();
callback();
}, delay);
};
}
return requestAnimFrame;
};
var polyfillCAF = function() {
var cancelAnimFrame = window.cancelAnimationFrame || window[theCSSPrefix.toLowerCase() + 'CancelAnimationFrame'];
if(_isMobile || !cancelAnimFrame) {
cancelAnimFrame = function(timeout) {
return window.clearTimeout(timeout);
};
}
return cancelAnimFrame;
};
//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;
},
swing: function(p) {
return (-Math.cos(p * Math.PI) / 2) + 0.5;
},
sqrt: function(p) {
return Math.sqrt(p);
},
outCubic: function(p) {
return (Math.pow((p - 1), 3) + 1);
},
//see https://www.desmos.com/calculator/tbr20s8vd2 for how I did this
bounce: function(p) {
var a;
if(p <= 0.5083) {
a = 3;
} else if(p <= 0.8489) {
a = 9;
} else if(p <= 0.96208) {
a = 27;
} else if(p <= 0.99981) {
a = 91;
} else {
return 1;
}
return 1 - Math.abs(3 * Math.cos(p * a * 1.028) / a);
}
};
/**
* Constructor.
*/
function Skrollr(options) {
documentElement = document.documentElement;
body = document.body;
detectCSSPrefix();
_instance = this;
options = options || {};
_constants = options.constants || {};
//We allow defining custom easings or overwrite existing.
if(options.easing) {
for(var e in options.easing) {
easings[e] = options.easing[e];
}
}
_edgeStrategy = options.edgeStrategy || 'set';
_listeners = {
//Function to be called right before rendering.
beforerender: options.beforerender,
//Function to be called right after finishing rendering.
render: options.render,
//Function to be called whenever an element with the `data-emit-events` attribute passes a keyframe.
keyframe: options.keyframe
};
//forceHeight is true by default
_forceHeight = options.forceHeight !== false;
if(_forceHeight) {
_scale = options.scale || 1;
}
_mobileDeceleration = options.mobileDeceleration || DEFAULT_MOBILE_DECELERATION;
_smoothScrollingEnabled = options.smoothScrolling !== false;
_smoothScrollingDuration = options.smoothScrollingDuration || DEFAULT_SMOOTH_SCROLLING_DURATION;
//Dummy object. Will be overwritten in the _render method when smooth scrolling is calculated.
_smoothScrolling = {
targetTop: _instance.getScrollTop()
};
//A custom check function may be passed.
_isMobile = ((options.mobileCheck || function() {
return (/Android|iPhone|iPad|iPod|BlackBerry/i).test(navigator.userAgent || navigator.vendor || window.opera);
})());
if(_isMobile) {
_skrollrBody = document.getElementById(options.skrollrBody || DEFAULT_SKROLLRBODY);
//Detect 3d transform if there's a skrollr-body (only needed for #skrollr-body).
if(_skrollrBody) {
_detect3DTransforms();
}
_initMobile();
_updateClass(documentElement, [SKROLLR_CLASS, SKROLLR_MOBILE_CLASS], [NO_SKROLLR_CLASS]);
} else {
_updateClass(documentElement, [SKROLLR_CLASS, SKROLLR_DESKTOP_CLASS], [NO_SKROLLR_CLASS]);
}
//Triggers parsing of elements and a first reflow.
_instance.refresh();
_addEvent(window, 'resize orientationchange', function() {
var width = documentElement.clientWidth;
var height = documentElement.clientHeight;
//Only reflow if the size actually changed (#271).
if(height !== _lastViewportHeight || width !== _lastViewportWidth) {
_lastViewportHeight = height;
_lastViewportWidth = width;
_requestReflow = true;
}
});
var requestAnimFrame = polyfillRAF();
//Let's go.
(function animloop(){
_render();
_animFrame = requestAnimFrame(animloop);
}());
return _instance;
}
/**
* (Re)parses some or all elements.
*/
Skrollr.prototype.refresh = function(elements) {
var elementIndex;
var elementsLength;
var ignoreID = false;
//Completely reparse anything without argument.
if(elements === undefined) {
//Ignore that some elements may already have a skrollable ID.
ignoreID = true;
_skrollables = [];
_skrollableIdCounter = 0;
elements = document.getElementsByTagName('*');
} else if(elements.length === undefined) {
//We also accept a single element as parameter.
elements = [elements];
}
elementIndex = 0;
elementsLength = elements.length;
for(; elementIndex < elementsLength; elementIndex++) {
var el = elements[elementIndex];
var anchorTarget = el;
var keyFrames = [];
//If this particular element should be smooth scrolled.
var smoothScrollThis = _smoothScrollingEnabled;
//The edge strategy for this particular element.
var edgeStrategy = _edgeStrategy;
//If this particular element should emit keyframe events.
var emitEvents = false;
//If we're reseting the counter, remove any old element ids that may be hanging around.
if(ignoreID && SKROLLABLE_ID_DOM_PROPERTY in el) {
delete el[SKROLLABLE_ID_DOM_PROPERTY];
}
if(!el.attributes) {
continue;
}
//Iterate over all attributes and search for key frame attributes.
var attributeIndex = 0;
var attributesLength = el.attributes.length;
for (; attributeIndex < attributesLength; attributeIndex++) {
var attr = el.attributes[attributeIndex];
if(attr.name === 'data-anchor-target') {
anchorTarget = document.querySelector(attr.value);
if(anchorTarget === null) {
throw 'Unable to find anchor target "' + attr.value + '"';
}
continue;
}
//Global smooth scrolling can be overridden by the element attribute.
if(attr.name === 'data-smooth-scrolling') {
smoothScrollThis = attr.value !== 'off';
continue;
}
//Global edge strategy can be overridden by the element attribute.
if(attr.name === 'data-edge-strategy') {
edgeStrategy = attr.value;
continue;
}
//Is this element tagged with the `data-emit-events` attribute?
if(attr.name === 'data-emit-events') {
emitEvents = true;
continue;
}
var match = attr.name.match(rxKeyframeAttribute);
if(match === null) {
continue;
}
var kf = {
props: attr.value,
//Point back to the element as well.
element: el,
//The name of the event which this keyframe will fire, if emitEvents is
eventType: attr.name.replace(rxCamelCase, rxCamelCaseFn)
};
keyFrames.push(kf);
var constant = match[1];
if(constant) {
//Strip the underscore prefix.
kf.constant = constant.substr(1);
}
//Get the key frame offset.
var offset = match[2];
//Is it a percentage offset?
if(/p$/.test(offset)) {
kf.isPercentage = true;
kf.offset = (offset.slice(0, -1) | 0) / 100;
} else {
kf.offset = (offset | 0);
}
var anchor1 = match[3];
//If second anchor is not set, the first will be taken for both.
var anchor2 = match[4] || anchor1;
//"absolute" (or "classic") mode, where numbers mean absolute scroll offset.
if(!anchor1 || anchor1 === ANCHOR_START || anchor1 === ANCHOR_END) {
kf.mode = 'absolute';
//data-end needs to be calculated after all key frames are known.
if(anchor1 === ANCHOR_END) {
kf.isEnd = true;
} else if(!kf.isPercentage) {
//For data-start we can already set the key frame w/o calculations.
//#59: "scale" options should only affect absolute mode.
kf.offset = kf.offset * _scale;
}
}
//"relative" mode, where numbers are relative to anchors.
else {
kf.mode = 'relative';
kf.anchors = [anchor1, anchor2];
}
}
//Does this element have key frames?
if(!keyFrames.length) {
continue;
}
//Will hold the original style and class attributes before we controlled the element (see #80).
var styleAttr, classAttr;
var id;
if(!ignoreID && SKROLLABLE_ID_DOM_PROPERTY in el) {
//We already have this element under control. Grab the corresponding skrollable id.
id = el[SKROLLABLE_ID_DOM_PROPERTY];
styleAttr = _skrollables[id].styleAttr;
classAttr = _skrollables[id].classAttr;
} else {
//It's an unknown element. Asign it a new skrollable id.
id = (el[SKROLLABLE_ID_DOM_PROPERTY] = _skrollableIdCounter++);
styleAttr = el.style.cssText;
classAttr = _getClass(el);
}
_skrollables[id] = {
element: el,
styleAttr: styleAttr,
classAttr: classAttr,
anchorTarget: anchorTarget,
keyFrames: keyFrames,
smoothScrolling: smoothScrollThis,
edgeStrategy: edgeStrategy,
emitEvents: emitEvents,
lastFrameIndex: -1
};
_updateClass(el, [SKROLLABLE_CLASS], []);
}
//Reflow for the first time.
_reflow();
//Now that we got all key frame numbers right, actually parse the properties.
elementIndex = 0;
elementsLength = elements.length;
for(; elementIndex < elementsLength; elementIndex++) {
var sk = _skrollables[elements[elementIndex][SKROLLABLE_ID_DOM_PROPERTY]];
if(sk === undefined) {
continue;
}
//Parse the property string to objects
_parseProps(sk);
//Fill key frames with missing properties from left and right
_fillProps(sk);
}
return _instance;
};
/**
* Transform "relative" mode to "absolute" mode.
* That is, calculate anchor position and offset of element.
*/
Skrollr.prototype.relativeToAbsolute = function(element, viewportAnchor, elementAnchor) {
var viewportHeight = documentElement.clientHeight;
var box = element.getBoundingClientRect();
var absolute = box.top;
//#100: IE doesn't supply "height" with getBoundingClientRect.
var boxHeight = box.bottom - box.top;
if(viewportAnchor === ANCHOR_BOTTOM) {
absolute -= viewportHeight;
} else if(viewportAnchor === ANCHOR_CENTER) {
absolute -= viewportHeight / 2;
}
if(elementAnchor === ANCHOR_BOTTOM) {
absolute += boxHeight;
} else if(elementAnchor === ANCHOR_CENTER) {
absolute += boxHeight / 2;
}
//Compensate scrolling since getBoundingClientRect is relative to viewport.
absolute += _instance.getScrollTop();
return (absolute + 0.5) | 0;
};
/**
* Animates scroll top to new position.
*/
Skrollr.prototype.animateTo = function(top, options) {
options = options || {};
var now = _now();
var scrollTop = _instance.getScrollTop();
var duration = options.duration === undefined ? DEFAULT_DURATION : options.duration;
//Setting this to a new value will automatically cause the current animation to stop, if any.
_scrollAnimation = {
startTop: scrollTop,
topDiff: top - scrollTop,
targetTop: top,
duration: duration,
startTime: now,
endTime: now + duration,
easing: easings[options.easing || DEFAULT_EASING],
done: options.done
};
//Don't queue the animation if there's nothing to animate.
if(!_scrollAnimation.topDiff) {
if(_scrollAnimation.done) {
_scrollAnimation.done.call(_instance, false);
}
_scrollAnimation = undefined;
}
return _instance;
};
/**
* Stops animateTo animation.
*/
Skrollr.prototype.stopAnimateTo = function() {
if(_scrollAnimation && _scrollAnimation.done) {
_scrollAnimation.done.call(_instance, true);
}
_scrollAnimation = undefined;
};
/**
* Returns if an animation caused by animateTo is currently running.
*/
Skrollr.prototype.isAnimatingTo = function() {
return !!_scrollAnimation;
};
Skrollr.prototype.isMobile = function() {
return _isMobile;
};
Skrollr.prototype.setScrollTop = function(top, force) {
_forceRender = (force === true);
if(_isMobile) {
_mobileOffset = Math.min(Math.max(top, 0), _maxKeyFrame);
} else {
window.scrollTo(0, top);
}
return _instance;
};
Skrollr.prototype.getScrollTop = function() {
if(_isMobile) {
return _mobileOffset;
} else {
return window.pageYOffset || documentElement.scrollTop || body.scrollTop || 0;
}
};
Skrollr.prototype.getMaxScrollTop = function() {
return _maxKeyFrame;
};
Skrollr.prototype.on = function(name, fn) {
_listeners[name] = fn;
return _instance;
};
Skrollr.prototype.off = function(name) {
delete _listeners[name];
return _instance;
};
Skrollr.prototype.destroy = function() {
var cancelAnimFrame = polyfillCAF();
cancelAnimFrame(_animFrame);
_removeAllEvents();
_updateClass(documentElement, [NO_SKROLLR_CLASS], [SKROLLR_CLASS, SKROLLR_DESKTOP_CLASS, SKROLLR_MOBILE_CLASS]);
var skrollableIndex = 0;
var skrollablesLength = _skrollables.length;
for(; skrollableIndex < skrollablesLength; skrollableIndex++) {
_reset(_skrollables[skrollableIndex].element);
}
documentElement.style.overflow = body.style.overflow = '';
documentElement.style.height = body.style.height = '';
if(_skrollrBody) {
skrollr.setStyle(_skrollrBody, 'transform', 'none');
}
_instance = undefined;
_skrollrBody = undefined;
_listeners = undefined;
_forceHeight = undefined;
_maxKeyFrame = 0;
_scale = 1;
_constants = undefined;
_mobileDeceleration = undefined;
_direction = 'down';
_lastTop = -1;
_lastViewportWidth = 0;
_lastViewportHeight = 0;
_requestReflow = false;
_scrollAnimation = undefined;
_smoothScrollingEnabled = undefined;
_smoothScrollingDuration = undefined;
_smoothScrolling = undefined;
_forceRender = undefined;
_skrollableIdCounter = 0;
_edgeStrategy = undefined;
_isMobile = false;
_mobileOffset = 0;
_translateZ = undefined;
};
/*
Private methods.
*/
var _initMobile = function() {
var initialElement;
var initialTouchY;
var initialTouchX;
var currentElement;
var currentTouchY;
var currentTouchX;
var lastTouchY;
var deltaY;
var initialTouchTime;
var currentTouchTime;
var lastTouchTime;
var deltaTime;
_addEvent(documentElement, [EVENT_TOUCHSTART, EVENT_TOUCHMOVE, EVENT_TOUCHCANCEL, EVENT_TOUCHEND].join(' '), function(e) {
var touch = e.changedTouches[0];
currentElement = e.target;
//We don't want text nodes.
while(currentElement.nodeType === 3) {
currentElement = currentElement.parentNode;
}
currentTouchY = touch.clientY;
currentTouchX = touch.clientX;
currentTouchTime = e.timeStamp;
if(!rxTouchIgnoreTags.test(currentElement.tagName)) {
e.preventDefault();
}
switch(e.type) {
case EVENT_TOUCHSTART:
//The last element we tapped on.
if(initialElement) {
initialElement.blur();
}
_instance.stopAnimateTo();
initialElement = currentElement;
initialTouchY = lastTouchY = currentTouchY;
initialTouchX = currentTouchX;
initialTouchTime = currentTouchTime;
break;
case EVENT_TOUCHMOVE:
//Prevent default event on touchIgnore elements in case they don't have focus yet.
if(rxTouchIgnoreTags.test(currentElement.tagName) && document.activeElement !== currentElement) {
e.preventDefault();
}
deltaY = currentTouchY - lastTouchY;
deltaTime = currentTouchTime - lastTouchTime;
_instance.setScrollTop(_mobileOffset - deltaY, true);
lastTouchY = currentTouchY;
lastTouchTime = currentTouchTime;
break;
default:
case EVENT_TOUCHCANCEL:
case EVENT_TOUCHEND:
var distanceY = initialTouchY - currentTouchY;
var distanceX = initialTouchX - currentTouchX;
var distance2 = distanceX * distanceX + distanceY * distanceY;
//Check if it was more like a tap (moved less than 7px).
if(distance2 < 49) {
if(!rxTouchIgnoreTags.test(initialElement.tagName)) {
initialElement.focus();
//It was a tap, click the element.
var clickEvent = document.createEvent('MouseEvents');
clickEvent.initMouseEvent('click', true, true, e.view, 1, touch.screenX, touch.screenY, touch.clientX, touch.clientY, e.ctrlKey, e.altKey, e.shiftKey, e.metaKey, 0, null);
initialElement.dispatchEvent(clickEvent);
}
return;
}
initialElement = undefined;
var speed = deltaY / deltaTime;
//Cap speed at 3 pixel/ms.
speed = Math.max(Math.min(speed, 3), -3);
var duration = Math.abs(speed / _mobileDeceleration);
var targetOffset = speed * duration + 0.5 * _mobileDeceleration * duration * duration;
var targetTop = _instance.getScrollTop() - targetOffset;
//Relative duration change for when scrolling above bounds.
var targetRatio = 0;
//Change duration proportionally when scrolling would leave bounds.
if(targetTop > _maxKeyFrame) {
targetRatio = (_maxKeyFrame - targetTop) / targetOffset;
targetTop = _maxKeyFrame;
} else if(targetTop < 0) {
targetRatio = -targetTop / targetOffset;
targetTop = 0;
}
duration = duration * (1 - targetRatio);
_instance.animateTo((targetTop + 0.5) | 0, {easing: 'outCubic', duration: duration});
break;
}
});
//Just in case there has already been some native scrolling, reset it.
window.scrollTo(0, 0);
documentElement.style.overflow = body.style.overflow = 'hidden';
};
/**
* Updates key frames which depend on others / need to be updated on resize.
* That is "end" in "absolute" mode and all key frames in "relative" mode.
* Also handles constants, because they may change on resize.
*/
var _updateDependentKeyFrames = function() {
var viewportHeight = documentElement.clientHeight;
var processedConstants = _processConstants();
var skrollable;
var element;
var anchorTarget;
var keyFrames;
var keyFrameIndex;
var keyFramesLength;
var kf;
var skrollableIndex;
var skrollablesLength;
var offset;
var constantValue;
//First process all relative-mode elements and find the max key frame.
skrollableIndex = 0;
skrollablesLength = _skrollables.length;
for(; skrollableIndex < skrollablesLength; skrollableIndex++) {
skrollable = _skrollables[skrollableIndex];
element = skrollable.element;
anchorTarget = skrollable.anchorTarget;
keyFrames = skrollable.keyFrames;
keyFrameIndex = 0;
keyFramesLength = keyFrames.length;
for(; keyFrameIndex < keyFramesLength; keyFrameIndex++) {
kf = keyFrames[keyFrameIndex];
offset = kf.offset;
constantValue = processedConstants[kf.constant] || 0;
kf.frame = offset;
if(kf.isPercentage) {
//Convert the offset to percentage of the viewport height.
offset = offset * viewportHeight;
//Absolute + percentage mode.
kf.frame = offset;
}
if(kf.mode === 'relative') {
_reset(element);
kf.frame = _instance.relativeToAbsolute(anchorTarget, kf.anchors[0], kf.anchors[1]) - offset;
_reset(element, true);
}
kf.frame += constantValue;
//Only search for max key frame when forceHeight is enabled.
if(_forceHeight) {
//Find the max key frame, but don't use one of the data-end ones for comparison.
if(!kf.isEnd && kf.frame > _maxKeyFrame) {
_maxKeyFrame = kf.frame;
}
}
}
}
//#133: The document can be larger than the maxKeyFrame we found.
_maxKeyFrame = Math.max(_maxKeyFrame, _getDocumentHeight());
//Now process all data-end keyframes.
skrollableIndex = 0;
skrollablesLength = _skrollables.length;
for(; skrollableIndex < skrollablesLength; skrollableIndex++) {
skrollable = _skrollables[skrollableIndex];
keyFrames = skrollable.keyFrames;
keyFrameIndex = 0;
keyFramesLength = keyFrames.length;
for(; keyFrameIndex < keyFramesLength; keyFrameIndex++) {
kf = keyFrames[keyFrameIndex];
constantValue = processedConstants[kf.constant] || 0;
if(kf.isEnd) {
kf.frame = _maxKeyFrame - kf.offset + constantValue;
}
}
skrollable.keyFrames.sort(_keyFrameComparator);
}
};
/**
* Calculates and sets the style properties for the element at the given frame.
* @param fakeFrame The frame to render at when smooth scrolling is enabled.
* @param actualFrame The actual frame we are at.
*/
var _calcSteps = function(fakeFrame, actualFrame) {
//Iterate over all skrollables.
var skrollableIndex = 0;
var skrollablesLength = _skrollables.length;
for(; skrollableIndex < skrollablesLength; skrollableIndex++) {
var skrollable = _skrollables[skrollableIndex];
var element = skrollable.element;
var frame = skrollable.smoothScrolling ? fakeFrame : actualFrame;
var frames = skrollable.keyFrames;
var framesLength = frames.length;
var firstFrame = frames[0];
var lastFrame = frames[frames.length - 1];
var beforeFirst = frame < firstFrame.frame;
var afterLast = frame > lastFrame.frame;
var firstOrLastFrame = beforeFirst ? firstFrame : lastFrame;
var emitEvents = skrollable.emitEvents;
var lastFrameIndex = skrollable.lastFrameIndex;
var key;
var value;
//If we are before/after the first/last frame, set the styles according to the given edge strategy.
if(beforeFirst || afterLast) {
//Check if we already handled this edge case last time.
//Note: using setScrollTop it's possible that we jumped from one edge to the other.
if(beforeFirst && skrollable.edge === -1 || afterLast && skrollable.edge === 1) {
continue;
}
//Add the skrollr-before or -after class.
if(beforeFirst) {
_updateClass(element, [SKROLLABLE_BEFORE_CLASS], [SKROLLABLE_AFTER_CLASS, SKROLLABLE_BETWEEN_CLASS]);
//This handles the special case where we exit the first keyframe.
if(emitEvents && lastFrameIndex > -1) {
_emitEvent(element, firstFrame.eventType, _direction);
skrollable.lastFrameIndex = -1;
}
} else {
_updateClass(element, [SKROLLABLE_AFTER_CLASS], [SKROLLABLE_BEFORE_CLASS, SKROLLABLE_BETWEEN_CLASS]);
//This handles the special case where we exit the last keyframe.
if(emitEvents && lastFrameIndex < framesLength) {
_emitEvent(element, lastFrame.eventType, _direction);
skrollable.lastFrameIndex = framesLength;
}
}
//Remember that we handled the edge case (before/after the first/last keyframe).
skrollable.edge = beforeFirst ? -1 : 1;
switch(skrollable.edgeStrategy) {
case 'reset':
_reset(element);
continue;
case 'ease':
//Handle this case like it would be exactly at first/last keyframe and just pass it on.
frame = firstOrLastFrame.frame;
break;
default:
case 'set':
var props = firstOrLastFrame.props;
for(key in props) {
if(hasProp.call(props, key)) {
value = _interpolateString(props[key].value);
//Set style or attribute.
if(key.indexOf('@') === 0) {
element.setAttribute(key.substr(1), value);
} else {
skrollr.setStyle(element, key, value);
}
}
}
continue;
}