forked from terwanerik/ScrollTrigger
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ScrollTrigger.js
704 lines (580 loc) · 18.8 KB
/
ScrollTrigger.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
/**
* Written by Erik Terwan on 03/07/16.
*
* Erik Terwan - development + design
* https://erikterwan.com
* https://github.com/terwanerik
*
* MIT license.
*/
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define([], factory);
} else if (typeof module === 'object' && module.exports) {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
module.exports = factory();
} else {
// Browser globals (root is window)
root.ScrollTrigger = factory();
}
}(this, function () {
'use strict';
return function(defaultOptions, bindTo, scrollIn) {
/**
* Trigger object, represents a single html element with the
* data-scroll tag. Stores the options given in that tag.
*/
var Trigger = function(_defaultOptions, _element) {
this.element = _element;
this.defaultOptions = _defaultOptions;
this.showCallback = null;
this.hideCallback = null;
this.visibleClass = 'visible';
this.hiddenClass = 'invisible';
this.addWidth = false;
this.addHeight = false;
this.once = false;
var xOffset = 0;
var yOffset = 0;
this.left = function(_this){
return function(){
return _this.element.getBoundingClientRect().left;
};
}(this);
this.top = function(_this){
return function(){
return _this.element.getBoundingClientRect().top;
};
}(this);
this.xOffset = function(_this){
return function(goingLeft){
var offset = xOffset;
// add the full width of the element to the left position, so the
// visibleClass is only added after the element is completely
// in the viewport
if (_this.addWidth && !goingLeft) {
offset += _this.width();
} else if (goingLeft && !_this.addWidth) {
offset -= _this.width();
}
return offset;
};
}(this);
this.yOffset = function(_this){
return function(goingUp){
var offset = yOffset;
// add the full height of the element to the top position, so the
// visibleClass is only added after the element is completely
// in the viewport
if (_this.addHeight && !goingUp) {
offset += _this.height();
} else if (goingUp && !_this.addHeight) {
offset -= _this.height();
}
return offset;
};
}(this);
this.width = function(_this) {
return function(){
return _this.element.offsetWidth;
};
}(this);
this.height = function(_this) {
return function(){
return _this.element.offsetHeight;
};
}(this);
this.reset = function(_this) {
return function() {
_this.removeClass(_this.visibleClass);
_this.removeClass(_this.hiddenClass);
};
}(this);
this.addClass = function(_this){
var addClass = function(className, didAddCallback) {
if (!_this.element.classList.contains(className)) {
_this.element.classList.add(className);
if ( typeof didAddCallback === 'function' ) {
didAddCallback();
}
}
};
var retroAddClass = function(className, didAddCallback) {
className = className.trim();
var regEx = new RegExp('(?:^|\\s)' + className + '(?:(\\s\\w)|$)', 'ig');
var oldClassName = _this.element.className;
if ( !regEx.test(oldClassName) ) {
_this.element.className += " " + className;
if ( typeof didAddCallback === 'function' ) {
didAddCallback();
}
}
};
return _this.element.classList ? addClass : retroAddClass;
}(this);
this.removeClass = function(_this){
var removeClass = function(className, didRemoveCallback) {
if (_this.element.classList.contains(className)) {
_this.element.classList.remove(className);
if ( typeof didRemoveCallback === 'function' ) {
didRemoveCallback();
}
}
};
var retroRemoveClass = function(className, didRemoveCallback) {
className = className.trim();
var regEx = new RegExp('(?:^|\\s)' + className + '(?:(\\s\\w)|$)', 'ig');
var oldClassName = _this.element.className;
if ( regEx.test(oldClassName) ) {
_this.element.className = oldClassName.replace(regEx, "$1").trim();
if ( typeof didRemoveCallback === 'function' ) {
didRemoveCallback();
}
}
};
return _this.element.classList ? removeClass : retroRemoveClass;
}(this);
this.init = function(_this){
return function(){
// set the default options
var options = _this.defaultOptions;
// parse the options given in the data-scroll attribute, if any
var optionString = _this.element.getAttribute('data-scroll');
if (options) {
if (options.toggle && options.toggle.visible) {
_this.visibleClass = options.toggle.visible;
}
if (options.toggle && options.toggle.hidden) {
_this.hiddenClass = options.toggle.hidden;
}
if (options.showCallback) {
_this.showCallback = options.showCallback;
}
if (options.hideCallback) {
_this.hideCallback = options.hideCallback;
}
if (options.centerHorizontal === true) {
xOffset = _this.element.offsetWidth / 2;
}
if (options.centerVertical === true) {
yOffset = _this.element.offsetHeight / 2;
}
if (options.offset && options.offset.x) {
xOffset+= options.offset.x;
}
if (options.offset && options.offset.y) {
yOffset+= options.offset.y;
}
if (options.addWidth) {
_this.addWidth = options.addWidth;
}
if (options.addHeight) {
_this.addHeight = options.addHeight;
}
if (options.once) {
_this.once = options.once;
}
}
// parse the boolean options
var parsedAddWidth = optionString.indexOf("addWidth") > -1;
var parsedAddHeight = optionString.indexOf("addHeight") > -1;
var parsedOnce = optionString.indexOf("once") > -1;
// check if the 'addHeight' was toggled via the data-scroll tag, that overrides the default settings object
if (_this.addWidth === false && parsedAddWidth === true) {
_this.addWidth = parsedAddWidth;
}
if (_this.addHeight === false && parsedAddHeight === true) {
_this.addHeight = parsedAddHeight;
}
if (_this.once === false && parsedOnce === true) {
_this.once = parsedOnce;
}
// parse callbacks
_this.showCallback = _this.element.hasAttribute('data-scroll-showCallback') ? _this.element.getAttribute('data-scroll-showCallback') : _this.showCallback;
_this.hideCallback = _this.element.hasAttribute('data-scroll-hideCallback') ? _this.element.getAttribute('data-scroll-hideCallback') : _this.hideCallback;
// split the options on the toggle() parameter
var classParts = optionString.split('toggle(');
if (classParts.length > 1) {
// the toggle() parameter was given, split it at ) to get the
// content inside the parentheses, then split them on the comma
var classes = classParts[1].split(')')[0].split(',');
// Check if trim exists if not, add the polyfill
// courtesy of MDN
if (!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
};
}
// trim and remove the dot
_this.visibleClass = classes[0].trim().replace('.', '');
_this.hiddenClass = classes[1].trim().replace('.', '');
}
// adds the half of the offsetWidth/Height to the x/yOffset
if (optionString.indexOf("centerHorizontal") > -1) {
xOffset = _this.element.offsetWidth / 2;
}
if (optionString.indexOf("centerVertical") > -1) {
yOffset = _this.element.offsetHeight / 2;
}
// split the options on the offset() parameter
var offsetParts = optionString.split('offset(');
if (offsetParts.length > 1) {
// the offset() parameter was given, split it at ) to get the
// content inside the parentheses, then split them on the comma
var offsets = offsetParts[1].split(')')[0].split(',');
// remove the px unit and parse as integer
xOffset += parseInt(offsets[0].replace('px', ''));
yOffset += parseInt(offsets[1].replace('px', ''));
}
// return this for chaining
return _this;
};
}(this);
};
// the element to detect the scroll in
this.scrollElement = window;
// the element to get the data-scroll elements from
this.bindElement = document.body;
// the scope to call the callbacks in, defaults to window
this.callScope = window;
// the Trigger objects
var triggers = [];
// attached callbacks for the requestAnimationFrame loop,
// this is handy for custom scroll based animation. So you
// don't have multiple, unnecessary loops going.
var attached = [];
// the previous scrollTop position, to determine if a user
// is scrolling up or down. Set that to -1 -1 so the loop
// always runs at least once
var previousScroll = {
left: -1,
top: -1
};
// the loop method to use, preferred window.requestAnimationFrame
var loop = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.oRequestAnimationFrame ||
function(callback){ setTimeout(callback, 1000 / 60); };
// if the requestAnimationFrame is looping
var isLooping = false;
/**
* Initializes the scrollTrigger
*/
var init = function(_this) {
return function(defaultOptions, bindTo, scrollIn) {
// check if bindTo is not undefined or null,
// otherwise use the document.body
if (bindTo != undefined && bindTo != null) {
_this.bindElement = bindTo;
} else {
_this.bindElement = document.body;
}
// check if the scrollIn is not undefined or null,
// otherwise use the window
if (scrollIn != undefined && scrollIn != null) {
_this.scrollElement = scrollIn;
} else {
_this.scrollElement = window;
}
// Initially bind all elements with the data-scroll attribute
_this.bind(_this.bindElement.querySelectorAll("[data-scroll]"));
// return 'this' for chaining
return _this;
};
}(this);
/**
* Binds new HTMLElement objects to the trigger array
*/
this.bind = function(_this) {
return function(elements) {
// check if an array is given
if (elements instanceof HTMLElement) {
// if it's a single HTMLElement just create an array
elements = [elements];
}
// get all trigger elements, e.g. all elements with
// the data-scroll attribute and turn it from a NodeList
// into a plain old array
var newTriggers = [].slice.call(elements);
// map all the triggers to Trigger objects, and initialize them
// so the options get parsed
newTriggers = newTriggers.map(function (element, index) {
var trigger = new Trigger(defaultOptions, element);
return trigger.init();
});
// add to the triggers array
triggers = triggers.concat(newTriggers);
if (triggers.length > 0 && isLooping == false) {
isLooping = true;
// start the update loop
update();
} else {
isLooping = false;
}
// return 'this' for chaining
return _this;
};
}(this);
/**
* Returns a trigger object from a htmlElement object (e.g. via querySelector())
*/
this.triggerFor = function(_this) {
return function(htmlElement){
var returnTrigger = null;
triggers.each(function(trigger, index) {
if (trigger.element == htmlElement) {
returnTrigger = trigger;
}
});
return returnTrigger;
};
}(this);
/**
* Removes a Trigger by its HTMLElement object, e.g via querySelector()
*/
this.destroy = function(_this) {
return function(htmlElement) {
triggers.each(function(trigger, index) {
if (trigger.element == htmlElement) {
triggers.splice(index, 1);
}
});
// return 'this' for chaining
return _this;
};
}(this);
/**
* Removes all Trigger objects from the Trigger array
*/
this.destroyAll = function(_this) {
return function() {
triggers = [];
// return 'this' for chaining
return _this;
};
}(this);
/**
* Resets a Trigger object, removes all added classes and then removes it from the triggers array. Like nothing
* ever happened..
*/
this.reset = function(_this) {
return function(htmlElement) {
var trigger = _this.triggerFor(htmlElement);
if (trigger != null) {
trigger.reset();
var index = triggers.indexOf(trigger);
if (index > -1) {
triggers.splice(index, 1);
}
}
// return 'this' for chaining
return _this;
};
}(this);
/**
* Does the same as .reset() but for all triggers
*/
this.resetAll = function(_this) {
return function() {
triggers.each(function(trigger, index) {
trigger.reset();
});
triggers = [];
// return 'this' for chaining
return _this;
};
}(this);
/**
* Attaches a callback that get's called every time
* the update method is called
*/
this.attach = function(_this) {
return function(callback) {
// add callback to array
attached.push(callback);
if (!isLooping) {
isLooping = true;
// start the update loop
update();
}
// return 'this' for chaining
return _this;
};
}(this);
/**
* Detaches a callback
*/
this.detach = function(_this) {
return function(callback) {
// remove callback from array
var index = attached.indexOf(callback);
if (index > -1) {
attached.splice(index, 1);
}
return _this;
};
}(this);
// store _this for use in the update function scope (strict)
var _this = this;
/**
* Gets called everytime the browser is ready for it, or when the user
* scrolls (on legacy browsers)
*/
function update() {
// FF and IE use the documentElement instead of body
var currentTop = !_this.bindElement.scrollTop ? document.documentElement.scrollTop : _this.bindElement.scrollTop;
var currentLeft = !_this.bindElement.scrollLeft ? document.documentElement.scrollLeft : _this.bindElement.scrollLeft;
// if the user scrolled
if (previousScroll.left != currentLeft || previousScroll.top != currentTop) {
_this.scrollDidChange();
}
if (triggers.length > 0 || attached.length > 0) {
isLooping = true;
// and loop again
loop(update);
} else {
isLooping = false;
}
}
this.scrollDidChange = function(_this) {
return function() {
var windowWidth = _this.scrollElement.innerWidth || _this.scrollElement.offsetWidth;
var windowHeight = _this.scrollElement.innerHeight || _this.scrollElement.offsetHeight;
// FF and IE use the documentElement instead of body
var currentTop = !_this.bindElement.scrollTop ? document.documentElement.scrollTop : _this.bindElement.scrollTop;
var currentLeft = !_this.bindElement.scrollLeft ? document.documentElement.scrollLeft : _this.bindElement.scrollLeft;
var onceTriggers = [];
// loop through all triggers
triggers.each(function(trigger, index){
var triggerLeft = trigger.left();
var triggerTop = trigger.top();
if (previousScroll.left > currentLeft) {
// scrolling left, so we subtract the xOffset
triggerLeft -= trigger.xOffset(true);
} else if (previousScroll.left < currentLeft) {
// scrolling right, so we add the xOffset
triggerLeft += trigger.xOffset(false);
}
if (previousScroll.top > currentTop) {
// scrolling up, so we subtract the yOffset
triggerTop -= trigger.yOffset(true);
} else if (previousScroll.top < currentTop){
// scrolling down so then we add the yOffset
triggerTop += trigger.yOffset(false);
}
// toggle the classes
if (triggerLeft < windowWidth && triggerLeft >= 0 &&
triggerTop < windowHeight && triggerTop >= 0) {
// the element is visible
trigger.addClass(trigger.visibleClass, function(){
if (trigger.showCallback) {
functionCall(trigger, trigger.showCallback);
}
});
trigger.removeClass(trigger.hiddenClass);
if (trigger.once) {
// remove trigger from triggers array
onceTriggers.push(trigger);
}
} else {
// the element is invisible
trigger.addClass(trigger.hiddenClass);
trigger.removeClass(trigger.visibleClass, function(){
if (trigger.hideCallback) {
functionCall(trigger, trigger.hideCallback);
}
});
}
});
// call the attached callbacks, if any
attached.each(function(callback) {
callback.call(_this, currentLeft, currentTop, windowWidth, windowHeight);
});
// remove the triggers that are 'once'
onceTriggers.each(function(trigger){
var index = triggers.indexOf(trigger);
if (index > -1) {
triggers.splice(index, 1);
}
});
// save the current scroll position
previousScroll.left = currentLeft;
previousScroll.top = currentTop;
};
}(this);
function functionCall(trigger, functionAsString) {
var params = functionAsString.split('(');
var method = params[0];
if (params.length > 1) {
params = params[1].split(')')[0]; // get the value between the parentheses
// check if there are multiple attributes
if (params.indexOf("', '") > -1) {
params = params.split("', '");
} else if (params.indexOf("','") > -1) {
params = params.split("','");
} else if (params.indexOf('", "') > -1) {
params = params.split('", "');
} else if (params.indexOf('","') > -1) {
params = params.split('","');
} else {
// nope, just a single parameter
params = [params];
}
} else {
params = [];
}
// remove all quotes from the parameters
params = params.map(function (param) {
return removeQuotes(param);
})
if (typeof _this.callScope[method] == "function") {
// function exists in the call scope so let's try to call it. Some methods don't like to have the HTMLElement
// passed as 'this', so retry without that if it fails.
try {
_this.callScope[method].apply(trigger.element, params);
} catch (e) {
// alright let's try again
try {
_this.callScope[method].apply(null, params);
} catch (e) {
// ah to bad.
}
}
}
}
// removes quotes from a string, e.g. turns 'foo' or "foo" into foo
// typeof foo is string
function removeQuotes(str) {
str = str + ""; // force a string
if (str[0] == '"') {
str = str.substr(1);
}
if (str[0] == "'") {
str = str.substr(1);
}
if (str[str.length - 1] == '"') {
str = str.substr(0, str.length - 1);
}
if (str[str.length - 1] == "'") {
str = str.substr(0, str.length - 1);
}
return str;
}
// Faster than .forEach
Array.prototype.each = function(a) {
var l = this.length;
for(var i = 0; i < l; i++) {
var e = this[i];
if (e) {
a(e,i);
}
}
};
return init(defaultOptions, bindTo, scrollIn);
};
}));