-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathscrollax.js
More file actions
873 lines (756 loc) · 21.3 KB
/
scrollax.js
File metadata and controls
873 lines (756 loc) · 21.3 KB
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
/**
* _______ _______ ______ _____ _______ _ _
* |______ | |_____/ | | | | |_____| \___/
* ______| |_____ | \_ |_____| |_____ |_____ | | _/ \_
*
* Parallax Scrolling Library
* http://iprodev.github.io/Scrollax.js
*
* @version: 1.0.0
* @released: July 21, 2015
*
* @author: iProDev (Hemn Chawroka)
* http://iprodev.com/
*
* Licensed under the MIT license.
* http://opensource.org/licenses/MIT
*
*/
(function(factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
// AMD
define(['jquery'], factory);
} else if (typeof exports !== 'undefined') {
// CommonJS
module.exports = factory(require('jquery'));
} else {
// Global
factory(jQuery);
}
}(function($) {
'use strict';
/**
* References.
*/
var ArrayProto = Array.prototype, ObjProto = Object.prototype,
// Create quick reference variables for speed access to core prototypes.
push = ArrayProto.push,
splice = ArrayProto.splice,
hasOwnProperty = ObjProto.hasOwnProperty,
// Global variables
namespace = 'Scrollax',
lownamespace = namespace.toLowerCase(),
numberRegExp = /[-+]?\d+(\.\d+)?/g,
transforms = ['translateX', 'translateY', 'rotate', 'rotateX', 'rotateY', 'rotateZ', 'skewX', 'skewY', 'scaleX', 'scaleY'],
// Global DOM References
$win = $(window),
$doc = $(document.body),
// Support indicators
transform, gpuAcceleration,
// Speed access to frequently called functions
position, bind, unbind;
/**
* Scrollax
*
* @class
*
* @param {Element} frame Scrolling frame.
*/
var Scrollax = function(frame, options, callbackMap) {
// Private variables
var self = this;
var $frame = frame && $(frame).eq(0) || $win;
var instances = Scrollax.instances;
var prevent = null;
frame = $frame[0];
// Check the contest existance
$.each(instances, function(instance, i) {
if (instance && instance.frame === frame) {
prevent = true;
}
});
// Send warn message to browser when the Frame is not available or initialized before
if (!frame || prevent) {
if (prevent) {
warn(namespace + ': Scrollax has been initialized for this frame!');
}
else {
warn(namespace + ': Frame is not available!');
}
return;
}
// Merge options
var o = $.extend({}, Scrollax.defaults, options);
var parents = [],
$parents = null,
parentSelector = o.parentSelector || '[data-' + lownamespace + '-parent]',
elementsSelector = o.elementsSelector || '[data-' + lownamespace + ']',
callbacks = {},
tmpArray = [],
resizeID,
frameIsWindow = isWindow(frame),
// Garbage collecting purposes
i, l, pi, pl, $freezer, timer, containsPerformanceClass, offset, isHorizontal, parentOffset, pos, parent, parentOptions, ratio, start, end, parallaxElements, parallaxable, el, properties, property, value, transformStyle, numbers;
// Expose variables
self.frame = frame;
self.options = o;
self.parents = parents;
self.initialized = false;
/**
* (Re)Loading function.
*
* Populate arrays, set sizes, add spies, ...
*
* @return {Object}
*/
function load() {
$parents = frameIsWindow ? $doc.find(parentSelector) : $frame.find(parentSelector);
// Reset parents
parents.length = 0;
isHorizontal = !!o.horizontal;
// Iterate through parents
$parents.each(parentEachHandler);
// Update scroll
scrollHandler();
if (o.performanceTrick) {
$freezer = frameIsWindow ? $doc : $frame;
}
// Trigger :load event
trigger('load');
return self;
}
self.reload = load;
/**
* Each parent handler
*
* @param {Int} i Parent index.
* @param {Node} element Parent DOM element.
*
* @return {Void}
*/
var parentEachHandler = function (i, element) {
var $parent = $(element),
parentOptions = getInlineOptions($(element)),
parent = {};
parent.element = element,
parent.options = parentOptions,
parent.parallaxElements = [];
$parent.find(elementsSelector).each(function(pI, pElement) {
var parallaxElement = getInlineOptions($(pElement));
parallaxElement.element = pElement;
push.call(parent.parallaxElements, parallaxElement);
});
push.call(parents, parent);
}
/**
* Window resize handler.
*
* @return {Void}
*/
function resizeHandler() {
if (resizeID) {
resizeID = clearTimeout(resizeID);
}
resizeID = setTimeout(function () {
self.reload();
});
};
/**
* Frame scrolling handler.
*
* @return {Void}
*/
function scrollHandler() {
var l = parents.length;
if (o.performanceTrick && $freezer) {
clearTimeout(timer);
if(!containsPerformanceClass) {
$freezer.addClass('scrollax-performance');
containsPerformanceClass = true;
}
timer = setTimeout(function(){
$freezer.removeClass('scrollax-performance');
containsPerformanceClass = false;
}, 100);
}
if (!l) {
return;
}
// Get frame offset
offset = getOffset(frame);
for (var i = 0; i < l; i++) {
parent = parents[i];
pos = position(parent.element, frame);
if (pos[isHorizontal ? 'right' : 'bottom'] < 0 || pos[isHorizontal ? 'left' : 'top'] > offset[isHorizontal ? 'width' : 'height']) {
continue;
}
parentOptions = parent.options;
parentOffset = parentOptions.offset || o.offset || 0;
start = pos[isHorizontal ? 'right' : 'bottom'];
end = pos[isHorizontal ? 'width' : 'height'];
// Calculate parent parallax ratio
ratio = (end - start + parentOffset) / end;
if (ratio < 0) {
start = pos[isHorizontal ? 'left' : 'top'];
end = offset[isHorizontal ? 'width' : 'height'];
// Calculate negative parent parallax ratio
ratio = -1 + (end - start + parentOffset) / end;
}
if (ratio > 1 || ratio < -1) {
continue;
}
parallax(parent, ratio, isHorizontal);
}
// Trigger :scroll event
trigger('scroll', offset);
}
self.scroll = scrollHandler;
/**
* Parallax handler.
*
* @param {Int} index Parent object.
* @param {Object} offset Scroll offset.
*
* @return {Void}
*/
function parallax(parent, ratio) {
parallaxElements = parent.parallaxElements;
var l = parallaxElements.length;
if(!l) {
return;
}
for (var i = 0; i < l; i++) {
parallaxable = parallaxElements[i];
el = parallaxable.element;
// Set needed styles to parallaxable element
styleHandler(el, parallaxable, ratio);
}
}
/**
* Style handler for parallaxable element.
*
* @param {Node} element Parallaxable DOM element.
* @param {Object} parallaxable Parallaxable options.
* @param {int} ratio Parallax ratio.
*
* @return {Int} Parent index, or -1 if not found.
*/
function styleHandler(element, parallaxable, ratio) {
properties = parallaxable.properties || (isHorizontal ? { 'translateX': '100%' } : { 'translateY': '100%' });
transformStyle = "";
for(property in properties) {
value = properties[property];
if (typeof value === 'number') {
value = value * ratio;
}
else if (typeof value === 'string') {
numbers = value.match(numberRegExp);
value = value;
for (i = 0, l = numbers.length; i < l; i++) {
value = value.replace(numbers[i], parseFloat(numbers[i] * ratio));
};
}
if ($.inArray(property, transforms) !== -1) {
transformStyle += property + '(' + value + ')';
}
else {
element.style[property] = property === 'opacity' ? within(ratio < 0 ? 1 + value : 1 - value, 0, 1) : value;
}
}
if (transformStyle) {
element.style[transform] = gpuAcceleration + transformStyle;
}
}
/**
* Get the index of an parent in parents.
*
* @param {Mixed} parent Parent DOM element.
*
* @return {Int} index, or -1 if not found.
*/
function getIndex(parent) {
return typeof parent !== 'undefined' ?
is_numeric(parent) ?
parent >= 0 && parent < parents.length ? parent : -1 :
$parents.index(parent) :
-1;
}
// Expose getIndex without lowering the compressibility of it,
// as it is used quite often throughout Scrollax.
self.getIndex = getIndex;
/**
* Trigger callbacks for event.
*
* @param {String} name Event name.
* @param {Mixed} argX Arguments passed to callbacks.
*
* @return {Void}
*/
function trigger(name, arg1) {
if (callbacks[name]) {
l = callbacks[name].length;
// Callbacks will be stored and executed from a temporary array to not
// break the execution queue when one of the callbacks unbinds itself.
tmpArray.length = 0;
for (i = 0; i < l; i++) {
push.call(tmpArray, callbacks[name][i]);
}
// Execute the callbacks
for (i = 0; i < l; i++) {
tmpArray[i].call(self, name, arg1);
}
}
}
/**
* Registers callbacks to be executed only once.
*
* @param {Mixed} name Event name, or callbacks map.
* @param {Mixed} fn Callback, or an array of callback functions.
*
* @return {Object}
*/
self.one = function (name, fn) {
function proxy() {
fn.apply(self, arguments);
self.off(name, proxy);
}
self.on(name, proxy);
return self;
};
/**
* Registers callbacks.
*
* @param {Mixed} name Event name, or callbacks map.
* @param {Mixed} fn Callback, or an array of callback functions.
*
* @return {Object}
*/
self.on = function (name, fn) {
// Callbacks map
if (typeof(name) === 'object') {
for (var key in name) {
if (hasOwnProperty.call(name, key)) {
self.on(key, name[key]);
}
}
// Callback
}
else if (typeof(fn) === 'function') {
var names = name.split(' ');
for (var n = 0, nl = names.length; n < nl; n++) {
callbacks[names[n]] = callbacks[names[n]] || [];
if (callbackIndex(names[n], fn) === -1) {
push.call(callbacks[names[n]], fn);
}
}
// Callbacks array
}
else if (typeof(fn) === 'array') {
for (var f = 0, fl = fn.length; f < fl; f++) {
self.on(name, fn[f]);
}
}
return self;
};
/**
* Remove one or all callbacks.
*
* @param {String} name Event name.
* @param {Mixed} fn Callback, or an array of callback functions. Omit to remove all callbacks.
*
* @return {Object}
*/
self.off = function (name, fn) {
if (fn instanceof Array) {
for (var f = 0, fl = fn.length; f < fl; f++) {
self.off(name, fn[f]);
}
}
else {
var names = name.split(' ');
for (var n = 0, nl = names.length; n < nl; n++) {
callbacks[names[n]] = callbacks[names[n]] || [];
if (typeof(fn) === 'undefined') {
callbacks[names[n]].length = 0;
}
else {
var index = callbackIndex(names[n], fn);
if (index !== -1) {
splice.call(callbacks[names[n]], index, 1);
}
}
}
}
return self;
};
/**
* Returns callback array index.
*
* @param {String} name Event name.
* @param {Function} fn Function
*
* @return {Int} Callback array index, or -1 if isn't registered.
*/
function callbackIndex(name, fn) {
for (var i = 0, l = callbacks[name].length; i < l; i++) {
if (callbacks[name][i] === fn) {
return i;
}
}
return -1;
}
/**
* Updates a signle or multiple option values.
*
* @param {Mixed} name Name of the option that should be updated, or object that will extend the options.
* @param {Mixed} value New option value.
*
* @return {Object}
*/
self.set = function (name, value) {
if ($.isPlainObject(name)) {
$.extend(o, name);
}
else if (hasOwnProperty.call(o, name)) {
o[name] = value;
}
// Reload
load();
return self;
};
/**
* Destroys instance and everything it created.
*
* @return {Object}
*/
self.destroy = function() {
// Unbind all events
unbind(window, 'resize', resizeHandler);
unbind(frame, 'scroll', scrollHandler);
// Remove this instance from instances
$.each(instances, function(instance, i) {
if (instance && instance.frame === frame) {
splice.call(Scrollax.instances, i, 1);
}
});
parents.length = 0;
self.initialized = false;
// Trigger :destroy event
trigger('destroy');
return self;
};
/**
* Initialize.
*
* @return {Object}
*/
self.init = function() {
if (self.initialized) {
return;
}
// Register callbacks map
self.on(callbackMap);
load();
// Bind all events
bind(window, 'resize', resizeHandler);
bind(frame, 'scroll', scrollHandler);
// Add this instance to all instances
push.call(Scrollax.instances, self);
self.initialized = true;
// Trigger :initialized event
trigger('initialized');
return self;
};
};
Scrollax.instances = [];
/**
* Send warning message to the browser.
*
* @param {String} message
*
* @return {Void}
*/
function warn(message) {
if (console && console.warn) {
console.warn(namespace + ': ' + message);
}
else {
throw (namespace + ': ' + message);
}
}
/**
* Get Offset.
*
* @param {String} message
*
* @return {Void}
*/
function getOffset(element) {
var isWin = !!('pageYOffset' in element);
return {
width: isWin ? (window.innerWidth
|| document.documentElement.clientWidth
|| document.body.clientWidth) : element.offsetWidth,
height: isWin ? (window.innerHeight
|| document.documentElement.clientHeight
|| document.body.clientHeight) : element.offsetHeight,
left: element[isWin ? 'pageXOffset' : 'scrollLeft'],
top: element[isWin ? 'pageYOffset' : 'scrollTop']
};
}
/**
* A JavaScript equivalent of PHP’s is_numeric.
*
* @param {Mixed} value
*
* @return {Boolean}
*/
function is_numeric(value) {
return (typeof(value) === 'number' || typeof(value) === 'string') && value !== '' && !isNaN(value);
}
/**
* Make sure that number is within the limits.
*
* @param {Number} number
* @param {Number} min
* @param {Number} max
*
* @return {Number}
*/
function within(number, min, max) {
return number < min ? min : number > max ? max : number;
}
/**
* Get element inline options.
*
* @param {Object} $element jQuery object with element.
*
* @return {Object}
*/
function getInlineOptions($element) {
var data = $element.data(lownamespace.toLowerCase());
return data && eval("({" + data + "})") || {};
}
/**
* Check whether value is a window object.
*
* Uses duck typing to determine window. Without IE8 all we need is:
*
* var type = Object.prototype.toString.call(val);
* return type === '[object global]' || type === '[object Window]' || type === '[object DOMWindow]';
*
* @param {Mixed} val
* @return {Boolean}
*/
function isWindow(val) {
/* jshint eqeqeq:false */
var doc, docWin;
return !!(
val
&& typeof val === 'object'
&& typeof val.window === 'object'
&& val.window == val
&& val.setTimeout
&& val.alert
&& (doc = val.document)
&& typeof doc === 'object'
&& (docWin = doc.defaultView || doc.parentWindow)
&& typeof docWin === 'object'
&& docWin == val
);
};
// Returns element's position object relative to document, window, or other elements.
(function () {
var k, doc, docEl, win, winTop, winLeft, box, relBox;
/**
* Poor man's shallow object extend;
*
* @param {Object} a
* @param {Object} b
* @return {Object}
*/
function extend(a, b) {
for (k in b) a[k] = b[k];
return a;
}
/**
* Returns element's position object with `left`, `top`, `bottom`, `right`,
* `width`, and `height` properties indicating the position and dimensions
* of element on a page, or relative to other element.
*
* @param {Element} element
* @param {Element} [relativeTo] Defaults to `document.documentElement`.
*
* @return {Object|null}
*/
position = function(element, relativeTo) {
doc = element.ownerDocument || element;
docEl = doc.documentElement;
win = isWindow(relativeTo) ? relativeTo : doc.defaultView || window;
// normalize arguments
relativeTo = !relativeTo || relativeTo === doc ? docEl : relativeTo;
winTop = (win.pageYOffset || docEl.scrollTop) - docEl.clientTop;
winLeft = (win.pageXOffset || docEl.scrollLeft) - docEl.clientLeft;
box = { top: 0, left: 0 };
if (element && element.getBoundingClientRect) {
// new object needed because DOMRect properties are read-only
box = extend({}, element.getBoundingClientRect());
// width & height don't exist in <IE9
box.width = box.right - box.left;
box.height = box.bottom - box.top;
} else {
return null;
}
// current box is already relative to window
if (relativeTo === win) return box;
// add window offsets, making the box relative to documentElement
box.top += winTop;
box.left += winLeft;
box.right += winLeft;
box.bottom += winTop;
// current box is already relative to documentElement
if (relativeTo === docEl) return box;
// subtract position of other element
relBox = position(relativeTo);
box.left -= relBox.left;
box.right -= relBox.left;
box.top -= relBox.top;
box.bottom -= relBox.top;
return box;
}
}());
// Event binding component with support for legacy browsers.
(function () {
/**
* Prevets default event action in IE8-.
*/
function preventDefault() {
this.returnValue = false;
}
/**
* Stops event propagation in IE8-.
*/
function stopPropagation() {
this.cancelBubble = true;
}
/**
* Bind `el` event `type` to `fn`.
*
* @param {Element} el
* @param {String} type
* @param {Function} fn
* @param {Boolean} [capture]
*
* @return {Function} `fn`
*/
bind = window.addEventListener ? function (el, type, fn, capture) {
el.addEventListener(type, fn, capture || false);
return fn;
} : function (el, type, fn) {
var fnid = type + fn;
el[fnid] = el[fnid] || function () {
var event = window.event;
event.target = event.srcElement;
event.preventDefault = preventDefault;
event.stopPropagation = stopPropagation;
fn.call(el, event);
};
el.attachEvent('on' + type, el[fnid]);
return fn;
};
/**
* Unbind `el` event `type`'s callback `fn`.
*
* @param {Element} el
* @param {String} type
* @param {Function} fn
* @param {Boolean} [capture]
*
* @return {Function} `fn`
*/
unbind = window.removeEventListener ? function (el, type, fn, capture) {
el.removeEventListener(type, fn, capture || false);
return fn;
} : function (el, type, fn) {
var fnid = type + fn;
el.detachEvent('on' + type, el[fnid]);
// clean up reference to handler function, but with a fallback
// because we can't delete window object properties
try {
delete el[fnid];
} catch (err) {
el[fnid] = undefined;
}
return fn;
};
}());
// Feature detects
(function () {
var prefixes = ['', 'webkit', 'moz', 'ms', 'o'];
var el = document.createElement('div');
function testProp(prop) {
for (var p = 0, pl = prefixes.length; p < pl; p++) {
var prefixedProp = prefixes[p] ? prefixes[p] + prop.charAt(0).toUpperCase() + prop.slice(1) : prop;
if (el.style[prefixedProp] != null) {
return prefixedProp;
}
}
}
// Global support indicators
transform = testProp('transform');
gpuAcceleration = testProp('perspective') ? 'translateZ(0) ' : '';
}());
// Default options
Scrollax.defaults = {
horizontal: false, // Enable for horizontal scrolling.
offset: 0, // Target area offset from start (top in vert., left in hor.).
parentSelector: null, // Select only PARENTs that match this selector.
elementsSelector: null, // Select only PARALLAX_ELEMENTS that match this selector.
performanceTrick: false // Use this option to optimize your scroll performance. This option will freeze CSS Animations and pointer events during scrolling
};
// Expose the Scrollax
window.Scrollax = Scrollax;
// Extend jQuery
$.fn.Scrollax = function (options, callbackMap) {
var method, methodArgs;
// Attributes logic
if (!$.isPlainObject(options)) {
if (typeof options === 'string' || options === false) {
method = options === false ? 'destroy' : options;
methodArgs = slice.call(arguments, 1);
}
options = {};
}
// Apply to all elements
return this.each(function (i, element) {
// Call with prevention against multiple instantiations
var plugin = $.data(element, lownamespace);
if (!plugin && !method) {
// Create a new object if it doesn't exist yet
plugin = $.data(element, lownamespace, new Scrollax(element, options, callbackMap).init());
}
else if (plugin && method) {
// Call method
if (plugin[method]) {
plugin[method].apply(plugin, methodArgs);
}
}
});
};
$.Scrollax = function(options, callbackMap) {
$win.Scrollax(options, callbackMap);
};
var css = '.scrollax-performance, .scrollax-performance *, .scrollax-performance *:before, .scrollax-performance *:after { pointer-events: none !important; -webkit-animation-play-state: paused !important; animation-play-state: paused !important; };',
head = document.head || document.getElementsByTagName('head')[0],
style = document.createElement('style');
style.type = 'text/css';
if (style.styleSheet){
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
head.appendChild(style);
// AMD requirement
return Scrollax;
}));