/
2.0.3_ScrollMagic.js
2774 lines (2632 loc) · 101 KB
/
2.0.3_ScrollMagic.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
/*!
* ScrollMagic v2.0.3 (2015-04-07)
* The javascript library for magical scroll interactions.
* (c) 2015 Jan Paepke (@janpaepke)
* Project Website: http://janpaepke.github.io/ScrollMagic
*
* @version 2.0.3
* @license Dual licensed under MIT license and GPL.
* @author Jan Paepke - e-mail@janpaepke.de
*
* @file ScrollMagic main library.
*/
/**
* @namespace ScrollMagic
*/
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(factory);
} else if (typeof exports === 'object') {
// CommonJS
module.exports = factory();
} else {
// Browser global
root.ScrollMagic = factory();
}
}(this, function () {
"use strict";
var ScrollMagic = function () {
_util.log(2, '(COMPATIBILITY NOTICE) -> As of ScrollMagic 2.0.0 you need to use \'new ScrollMagic.Controller()\' to create a new controller instance. Use \'new ScrollMagic.Scene()\' to instance a scene.');
};
ScrollMagic.version = "2.0.3";
// TODO: temporary workaround for chrome's scroll jitter bug
window.addEventListener("mousewheel", function () {});
// global const
var PIN_SPACER_ATTRIBUTE = "data-scrollmagic-pin-spacer";
/**
* The main class that is needed once per scroll container.
*
* @class
*
* @example
* // basic initialization
* var controller = new ScrollMagic.Controller();
*
* // passing options
* var controller = new ScrollMagic.Controller({container: "#myContainer", loglevel: 3});
*
* @param {object} [options] - An object containing one or more options for the controller.
* @param {(string|object)} [options.container=window] - A selector, DOM object that references the main container for scrolling.
* @param {boolean} [options.vertical=true] - Sets the scroll mode to vertical (`true`) or horizontal (`false`) scrolling.
* @param {object} [options.globalSceneOptions={}] - These options will be passed to every Scene that is added to the controller using the addScene method. For more information on Scene options see {@link ScrollMagic.Scene}.
* @param {number} [options.loglevel=2] Loglevel for debugging. Note that logging is disabled in the minified version of ScrollMagic.
** `0` => silent
** `1` => errors
** `2` => errors, warnings
** `3` => errors, warnings, debuginfo
* @param {boolean} [options.refreshInterval=100] - Some changes don't call events by default, like changing the container size or moving a scene trigger element.
This interval polls these parameters to fire the necessary events.
If you don't use custom containers, trigger elements or have static layouts, where the positions of the trigger elements don't change, you can set this to 0 disable interval checking and improve performance.
*
*/
ScrollMagic.Controller = function (options) {
/*
* ----------------------------------------------------------------
* settings
* ----------------------------------------------------------------
*/
var
NAMESPACE = "ScrollMagic.Controller",
SCROLL_DIRECTIONS = {
f: "FORWARD",
r: "REVERSE",
p: "PAUSED"
},
DEFAULT_OPTIONS = CONTROLLER_OPTIONS.defaults;
/*
* ----------------------------------------------------------------
* private vars
* ----------------------------------------------------------------
*/
var
Controller = this,
_options = _util.extend({}, DEFAULT_OPTIONS, options),
_sceneObjects = [],
_updateScenesOnNextCycle = false,
// can be boolean (true => all scenes) or an array of scenes to be updated
_scrollPos = 0,
_scrollDirection = SCROLL_DIRECTIONS.p,
_isDocument = true,
_viewPortSize = 0,
_enabled = true,
_updateTimeout, _refreshTimeout;
/*
* ----------------------------------------------------------------
* private functions
* ----------------------------------------------------------------
*/
/**
* Internal constructor function of the ScrollMagic Controller
* @private
*/
var construct = function () {
for (var key in _options) {
if (!DEFAULT_OPTIONS.hasOwnProperty(key)) {
log(2, "WARNING: Unknown option \"" + key + "\"");
delete _options[key];
}
}
_options.container = _util.get.elements(_options.container)[0];
// check ScrollContainer
if (!_options.container) {
log(1, "ERROR creating object " + NAMESPACE + ": No valid scroll container supplied");
throw NAMESPACE + " init failed."; // cancel
}
_isDocument = _options.container === window || _options.container === document.body || !document.body.contains(_options.container);
// normalize to window
if (_isDocument) {
_options.container = window;
}
// update container size immediately
_viewPortSize = getViewportSize();
// set event handlers
_options.container.addEventListener("resize", onChange);
_options.container.addEventListener("scroll", onChange);
_options.refreshInterval = parseInt(_options.refreshInterval) || DEFAULT_OPTIONS.refreshInterval;
scheduleRefresh();
log(3, "added new " + NAMESPACE + " controller (v" + ScrollMagic.version + ")");
};
/**
* Schedule the next execution of the refresh function
* @private
*/
var scheduleRefresh = function () {
if (_options.refreshInterval > 0) {
_refreshTimeout = window.setTimeout(refresh, _options.refreshInterval);
}
};
/**
* Default function to get scroll pos - overwriteable using `Controller.scrollPos(newFunction)`
* @private
*/
var getScrollPos = function () {
return _options.vertical ? _util.get.scrollTop(_options.container) : _util.get.scrollLeft(_options.container);
};
/**
* Returns the current viewport Size (width vor horizontal, height for vertical)
* @private
*/
var getViewportSize = function () {
return _options.vertical ? _util.get.height(_options.container) : _util.get.width(_options.container);
};
/**
* Default function to set scroll pos - overwriteable using `Controller.scrollTo(newFunction)`
* Make available publicly for pinned mousewheel workaround.
* @private
*/
var setScrollPos = this._setScrollPos = function (pos) {
if (_options.vertical) {
if (_isDocument) {
window.scrollTo(_util.get.scrollLeft(), pos);
} else {
_options.container.scrollTop = pos;
}
} else {
if (_isDocument) {
window.scrollTo(pos, _util.get.scrollTop());
} else {
_options.container.scrollLeft = pos;
}
}
};
/**
* Handle updates in cycles instead of on scroll (performance)
* @private
*/
var updateScenes = function () {
if (_enabled && _updateScenesOnNextCycle) {
// determine scenes to update
var scenesToUpdate = _util.type.Array(_updateScenesOnNextCycle) ? _updateScenesOnNextCycle : _sceneObjects.slice(0);
// reset scenes
_updateScenesOnNextCycle = false;
var oldScrollPos = _scrollPos;
// update scroll pos now instead of onChange, as it might have changed since scheduling (i.e. in-browser smooth scroll)
_scrollPos = Controller.scrollPos();
var deltaScroll = _scrollPos - oldScrollPos;
if (deltaScroll !== 0) { // scroll position changed?
_scrollDirection = (deltaScroll > 0) ? SCROLL_DIRECTIONS.f : SCROLL_DIRECTIONS.r;
}
// reverse order of scenes if scrolling reverse
if (_scrollDirection === SCROLL_DIRECTIONS.r) {
scenesToUpdate.reverse();
}
// update scenes
scenesToUpdate.forEach(function (scene, index) {
log(3, "updating Scene " + (index + 1) + "/" + scenesToUpdate.length + " (" + _sceneObjects.length + " total)");
scene.update(true);
});
if (scenesToUpdate.length === 0 && _options.loglevel >= 3) {
log(3, "updating 0 Scenes (nothing added to controller)");
}
}
};
/**
* Initializes rAF callback
* @private
*/
var debounceUpdate = function () {
_updateTimeout = _util.rAF(updateScenes);
};
/**
* Handles Container changes
* @private
*/
var onChange = function (e) {
log(3, "event fired causing an update:", e.type);
if (e.type == "resize") {
// resize
_viewPortSize = getViewportSize();
_scrollDirection = SCROLL_DIRECTIONS.p;
}
// schedule update
if (_updateScenesOnNextCycle !== true) {
_updateScenesOnNextCycle = true;
debounceUpdate();
}
};
var refresh = function () {
if (!_isDocument) {
// simulate resize event. Only works for viewport relevant param (performance)
if (_viewPortSize != getViewportSize()) {
var resizeEvent;
try {
resizeEvent = new Event('resize', {
bubbles: false,
cancelable: false
});
} catch (e) { // stupid IE
resizeEvent = document.createEvent("Event");
resizeEvent.initEvent("resize", false, false);
}
_options.container.dispatchEvent(resizeEvent);
}
}
_sceneObjects.forEach(function (scene, index) { // refresh all scenes
scene.refresh();
});
scheduleRefresh();
};
/**
* Send a debug message to the console.
* provided publicly with _log for plugins
* @private
*
* @param {number} loglevel - The loglevel required to initiate output for the message.
* @param {...mixed} output - One or more variables that should be passed to the console.
*/
var log = this._log = function (loglevel, output) {
if (_options.loglevel >= loglevel) {
Array.prototype.splice.call(arguments, 1, 0, "(" + NAMESPACE + ") ->");
_util.log.apply(window, arguments);
}
};
// for scenes we have getters for each option, but for the controller we don't, so we need to make it available externally for plugins
this._options = _options;
/**
* Sort scenes in ascending order of their start offset.
* @private
*
* @param {array} ScenesArray - an array of ScrollMagic Scenes that should be sorted
* @return {array} The sorted array of Scenes.
*/
var sortScenes = function (ScenesArray) {
if (ScenesArray.length <= 1) {
return ScenesArray;
} else {
var scenes = ScenesArray.slice(0);
scenes.sort(function (a, b) {
return a.scrollOffset() > b.scrollOffset() ? 1 : -1;
});
return scenes;
}
};
/**
* ----------------------------------------------------------------
* public functions
* ----------------------------------------------------------------
*/
/**
* Add one ore more scene(s) to the controller.
* This is the equivalent to `Scene.addTo(controller)`.
* @public
* @example
* // with a previously defined scene
* controller.addScene(scene);
*
* // with a newly created scene.
* controller.addScene(new ScrollMagic.Scene({duration : 0}));
*
* // adding multiple scenes
* controller.addScene([scene, scene2, new ScrollMagic.Scene({duration : 0})]);
*
* @param {(ScrollMagic.Scene|array)} newScene - ScrollMagic Scene or Array of Scenes to be added to the controller.
* @return {Controller} Parent object for chaining.
*/
this.addScene = function (newScene) {
if (_util.type.Array(newScene)) {
newScene.forEach(function (scene, index) {
Controller.addScene(scene);
});
} else if (newScene instanceof ScrollMagic.Scene) {
if (newScene.controller() !== Controller) {
newScene.addTo(Controller);
} else if (_sceneObjects.indexOf(newScene) < 0) {
// new scene
_sceneObjects.push(newScene); // add to array
_sceneObjects = sortScenes(_sceneObjects); // sort
newScene.on("shift.controller_sort", function () { // resort whenever scene moves
_sceneObjects = sortScenes(_sceneObjects);
});
// insert Global defaults.
for (var key in _options.globalSceneOptions) {
if (newScene[key]) {
newScene[key].call(newScene, _options.globalSceneOptions[key]);
}
}
log(3, "adding Scene (now " + _sceneObjects.length + " total)");
}
} else {
log(1, "ERROR: invalid argument supplied for '.addScene()'");
}
return Controller;
};
/**
* Remove one ore more scene(s) from the controller.
* This is the equivalent to `Scene.remove()`.
* @public
* @example
* // remove a scene from the controller
* controller.removeScene(scene);
*
* // remove multiple scenes from the controller
* controller.removeScene([scene, scene2, scene3]);
*
* @param {(ScrollMagic.Scene|array)} Scene - ScrollMagic Scene or Array of Scenes to be removed from the controller.
* @returns {Controller} Parent object for chaining.
*/
this.removeScene = function (Scene) {
if (_util.type.Array(Scene)) {
Scene.forEach(function (scene, index) {
Controller.removeScene(scene);
});
} else {
var index = _sceneObjects.indexOf(Scene);
if (index > -1) {
Scene.off("shift.controller_sort");
_sceneObjects.splice(index, 1);
log(3, "removing Scene (now " + _sceneObjects.length + " left)");
Scene.remove();
}
}
return Controller;
};
/**
* Update one ore more scene(s) according to the scroll position of the container.
* This is the equivalent to `Scene.update()`.
* The update method calculates the scene's start and end position (based on the trigger element, trigger hook, duration and offset) and checks it against the current scroll position of the container.
* It then updates the current scene state accordingly (or does nothing, if the state is already correct) – Pins will be set to their correct position and tweens will be updated to their correct progress.
* _**Note:** This method gets called constantly whenever Controller detects a change. The only application for you is if you change something outside of the realm of ScrollMagic, like moving the trigger or changing tween parameters._
* @public
* @example
* // update a specific scene on next cycle
* controller.updateScene(scene);
*
* // update a specific scene immediately
* controller.updateScene(scene, true);
*
* // update multiple scenes scene on next cycle
* controller.updateScene([scene1, scene2, scene3]);
*
* @param {ScrollMagic.Scene} Scene - ScrollMagic Scene or Array of Scenes that is/are supposed to be updated.
* @param {boolean} [immediately=false] - If `true` the update will be instant, if `false` it will wait until next update cycle.
This is useful when changing multiple properties of the scene - this way it will only be updated once all new properties are set (updateScenes).
* @return {Controller} Parent object for chaining.
*/
this.updateScene = function (Scene, immediately) {
if (_util.type.Array(Scene)) {
Scene.forEach(function (scene, index) {
Controller.updateScene(scene, immediately);
});
} else {
if (immediately) {
Scene.update(true);
} else if (_updateScenesOnNextCycle !== true && Scene instanceof ScrollMagic.Scene) { // if _updateScenesOnNextCycle is true, all connected scenes are already scheduled for update
// prep array for next update cycle
_updateScenesOnNextCycle = _updateScenesOnNextCycle || [];
if (_updateScenesOnNextCycle.indexOf(Scene) == -1) {
_updateScenesOnNextCycle.push(Scene);
}
_updateScenesOnNextCycle = sortScenes(_updateScenesOnNextCycle); // sort
debounceUpdate();
}
}
return Controller;
};
/**
* Updates the controller params and calls updateScene on every scene, that is attached to the controller.
* See `Controller.updateScene()` for more information about what this means.
* In most cases you will not need this function, as it is called constantly, whenever ScrollMagic detects a state change event, like resize or scroll.
* The only application for this method is when ScrollMagic fails to detect these events.
* One application is with some external scroll libraries (like iScroll) that move an internal container to a negative offset instead of actually scrolling. In this case the update on the controller needs to be called whenever the child container's position changes.
* For this case there will also be the need to provide a custom function to calculate the correct scroll position. See `Controller.scrollPos()` for details.
* @public
* @example
* // update the controller on next cycle (saves performance due to elimination of redundant updates)
* controller.update();
*
* // update the controller immediately
* controller.update(true);
*
* @param {boolean} [immediately=false] - If `true` the update will be instant, if `false` it will wait until next update cycle (better performance)
* @return {Controller} Parent object for chaining.
*/
this.update = function (immediately) {
onChange({
type: "resize"
}); // will update size and set _updateScenesOnNextCycle to true
if (immediately) {
updateScenes();
}
return Controller;
};
/**
* Scroll to a numeric scroll offset, a DOM element, the start of a scene or provide an alternate method for scrolling.
* For vertical controllers it will change the top scroll offset and for horizontal applications it will change the left offset.
* @public
*
* @since 1.1.0
* @example
* // scroll to an offset of 100
* controller.scrollTo(100);
*
* // scroll to a DOM element
* controller.scrollTo("#anchor");
*
* // scroll to the beginning of a scene
* var scene = new ScrollMagic.Scene({offset: 200});
* controller.scrollTo(scene);
*
* // define a new scroll position modification function (jQuery animate instead of jump)
* controller.scrollTo(function (newScrollPos) {
* $("body").animate({scrollTop: newScrollPos});
* });
* controller.scrollTo(100); // call as usual, but the new function will be used instead
*
* // define a new scroll function with an additional parameter
* controller.scrollTo(function (newScrollPos, message) {
* console.log(message);
* $(this).animate({scrollTop: newScrollPos});
* });
* // call as usual, but supply an extra parameter to the defined custom function
* controller.scrollTo(100, "my message");
*
* // define a new scroll function with an additional parameter containing multiple variables
* controller.scrollTo(function (newScrollPos, options) {
* someGlobalVar = options.a + options.b;
* $(this).animate({scrollTop: newScrollPos});
* });
* // call as usual, but supply an extra parameter containing multiple options
* controller.scrollTo(100, {a: 1, b: 2});
*
* // define a new scroll function with a callback supplied as an additional parameter
* controller.scrollTo(function (newScrollPos, callback) {
* $(this).animate({scrollTop: newScrollPos}, 400, "swing", callback);
* });
* // call as usual, but supply an extra parameter, which is used as a callback in the previously defined custom scroll function
* controller.scrollTo(100, function() {
* console.log("scroll has finished.");
* });
*
* @param {mixed} scrollTarget - The supplied argument can be one of these types:
* 1. `number` -> The container will scroll to this new scroll offset.
* 2. `string` or `object` -> Can be a selector or a DOM object.
* The container will scroll to the position of this element.
* 3. `ScrollMagic Scene` -> The container will scroll to the start of this scene.
* 4. `function` -> This function will be used for future scroll position modifications.
* This provides a way for you to change the behaviour of scrolling and adding new behaviour like animation. The function receives the new scroll position as a parameter and a reference to the container element using `this`.
* It may also optionally receive an optional additional parameter (see below)
* _**NOTE:**
* All other options will still work as expected, using the new function to scroll._
* @param {mixed} [additionalParameter] - If a custom scroll function was defined (see above 4.), you may want to supply additional parameters to it, when calling it. You can do this using this parameter – see examples for details. Please note, that this parameter will have no effect, if you use the default scrolling function.
* @returns {Controller} Parent object for chaining.
*/
this.scrollTo = function (scrollTarget, additionalParameter) {
if (_util.type.Number(scrollTarget)) { // excecute
setScrollPos.call(_options.container, scrollTarget, additionalParameter);
} else if (scrollTarget instanceof ScrollMagic.Scene) { // scroll to scene
if (scrollTarget.controller() === Controller) { // check if the controller is associated with this scene
Controller.scrollTo(scrollTarget.scrollOffset(), additionalParameter);
} else {
log(2, "scrollTo(): The supplied scene does not belong to this controller. Scroll cancelled.", scrollTarget);
}
} else if (_util.type.Function(scrollTarget)) { // assign new scroll function
setScrollPos = scrollTarget;
} else { // scroll to element
var elem = _util.get.elements(scrollTarget)[0];
if (elem) {
// if parent is pin spacer, use spacer position instead so correct start position is returned for pinned elements.
while (elem.parentNode.hasAttribute(PIN_SPACER_ATTRIBUTE)) {
elem = elem.parentNode;
}
var
param = _options.vertical ? "top" : "left",
// which param is of interest ?
containerOffset = _util.get.offset(_options.container),
// container position is needed because element offset is returned in relation to document, not in relation to container.
elementOffset = _util.get.offset(elem);
if (!_isDocument) { // container is not the document root, so substract scroll Position to get correct trigger element position relative to scrollcontent
containerOffset[param] -= Controller.scrollPos();
}
Controller.scrollTo(elementOffset[param] - containerOffset[param], additionalParameter);
} else {
log(2, "scrollTo(): The supplied argument is invalid. Scroll cancelled.", scrollTarget);
}
}
return Controller;
};
/**
* **Get** the current scrollPosition or **Set** a new method to calculate it.
* -> **GET**:
* When used as a getter this function will return the current scroll position.
* To get a cached value use Controller.info("scrollPos"), which will be updated in the update cycle.
* For vertical controllers it will return the top scroll offset and for horizontal applications it will return the left offset.
*
* -> **SET**:
* When used as a setter this method prodes a way to permanently overwrite the controller's scroll position calculation.
* A typical usecase is when the scroll position is not reflected by the containers scrollTop or scrollLeft values, but for example by the inner offset of a child container.
* Moving a child container inside a parent is a commonly used method for several scrolling frameworks, including iScroll.
* By providing an alternate calculation function you can make sure ScrollMagic receives the correct scroll position.
* Please also bear in mind that your function should return y values for vertical scrolls an x for horizontals.
*
* To change the current scroll position please use `Controller.scrollTo()`.
* @public
*
* @example
* // get the current scroll Position
* var scrollPos = controller.scrollPos();
*
* // set a new scroll position calculation method
* controller.scrollPos(function () {
* return this.info("vertical") ? -mychildcontainer.y : -mychildcontainer.x
* });
*
* @param {function} [scrollPosMethod] - The function to be used for the scroll position calculation of the container.
* @returns {(number|Controller)} Current scroll position or parent object for chaining.
*/
this.scrollPos = function (scrollPosMethod) {
if (!arguments.length) { // get
return getScrollPos.call(Controller);
} else { // set
if (_util.type.Function(scrollPosMethod)) {
getScrollPos = scrollPosMethod;
} else {
log(2, "Provided value for method 'scrollPos' is not a function. To change the current scroll position use 'scrollTo()'.");
}
}
return Controller;
};
/**
* **Get** all infos or one in particular about the controller.
* @public
* @example
* // returns the current scroll position (number)
* var scrollPos = controller.info("scrollPos");
*
* // returns all infos as an object
* var infos = controller.info();
*
* @param {string} [about] - If passed only this info will be returned instead of an object containing all.
Valid options are:
** `"size"` => the current viewport size of the container
** `"vertical"` => true if vertical scrolling, otherwise false
** `"scrollPos"` => the current scroll position
** `"scrollDirection"` => the last known direction of the scroll
** `"container"` => the container element
** `"isDocument"` => true if container element is the document.
* @returns {(mixed|object)} The requested info(s).
*/
this.info = function (about) {
var values = {
size: _viewPortSize,
// contains height or width (in regard to orientation);
vertical: _options.vertical,
scrollPos: _scrollPos,
scrollDirection: _scrollDirection,
container: _options.container,
isDocument: _isDocument
};
if (!arguments.length) { // get all as an object
return values;
} else if (values[about] !== undefined) {
return values[about];
} else {
log(1, "ERROR: option \"" + about + "\" is not available");
return;
}
};
/**
* **Get** or **Set** the current loglevel option value.
* @public
*
* @example
* // get the current value
* var loglevel = controller.loglevel();
*
* // set a new value
* controller.loglevel(3);
*
* @param {number} [newLoglevel] - The new loglevel setting of the Controller. `[0-3]`
* @returns {(number|Controller)} Current loglevel or parent object for chaining.
*/
this.loglevel = function (newLoglevel) {
if (!arguments.length) { // get
return _options.loglevel;
} else if (_options.loglevel != newLoglevel) { // set
_options.loglevel = newLoglevel;
}
return Controller;
};
/**
* **Get** or **Set** the current enabled state of the controller.
* This can be used to disable all Scenes connected to the controller without destroying or removing them.
* @public
*
* @example
* // get the current value
* var enabled = controller.enabled();
*
* // disable the controller
* controller.enabled(false);
*
* @param {boolean} [newState] - The new enabled state of the controller `true` or `false`.
* @returns {(boolean|Controller)} Current enabled state or parent object for chaining.
*/
this.enabled = function (newState) {
if (!arguments.length) { // get
return _enabled;
} else if (_enabled != newState) { // set
_enabled = !! newState;
Controller.updateScene(_sceneObjects, true);
}
return Controller;
};
/**
* Destroy the Controller, all Scenes and everything.
* @public
*
* @example
* // without resetting the scenes
* controller = controller.destroy();
*
* // with scene reset
* controller = controller.destroy(true);
*
* @param {boolean} [resetScenes=false] - If `true` the pins and tweens (if existent) of all scenes will be reset.
* @returns {null} Null to unset handler variables.
*/
this.destroy = function (resetScenes) {
window.clearTimeout(_refreshTimeout);
var i = _sceneObjects.length;
while (i--) {
_sceneObjects[i].destroy(resetScenes);
}
_options.container.removeEventListener("resize", onChange);
_options.container.removeEventListener("scroll", onChange);
_util.cAF(_updateTimeout);
log(3, "destroyed " + NAMESPACE + " (reset: " + (resetScenes ? "true" : "false") + ")");
return null;
};
// INIT
construct();
return Controller;
};
// store pagewide controller options
var CONTROLLER_OPTIONS = {
defaults: {
container: window,
vertical: true,
globalSceneOptions: {},
loglevel: 2,
refreshInterval: 100
}
};
/*
* method used to add an option to ScrollMagic Scenes.
*/
ScrollMagic.Controller.addOption = function (name, defaultValue) {
CONTROLLER_OPTIONS.defaults[name] = defaultValue;
};
// instance extension function for plugins
ScrollMagic.Controller.extend = function (extension) {
var oldClass = this;
ScrollMagic.Controller = function () {
oldClass.apply(this, arguments);
this.$super = _util.extend({}, this); // copy parent state
return extension.apply(this, arguments) || this;
};
_util.extend(ScrollMagic.Controller, oldClass); // copy properties
ScrollMagic.Controller.prototype = oldClass.prototype; // copy prototype
ScrollMagic.Controller.prototype.constructor = ScrollMagic.Controller; // restore constructor
};
/**
* A Scene defines where the controller should react and how.
*
* @class
*
* @example
* // create a standard scene and add it to a controller
* new ScrollMagic.Scene()
* .addTo(controller);
*
* // create a scene with custom options and assign a handler to it.
* var scene = new ScrollMagic.Scene({
* duration: 100,
* offset: 200,
* triggerHook: "onEnter",
* reverse: false
* });
*
* @param {object} [options] - Options for the Scene. The options can be updated at any time.
Instead of setting the options for each scene individually you can also set them globally in the controller as the controllers `globalSceneOptions` option. The object accepts the same properties as the ones below.
When a scene is added to the controller the options defined using the Scene constructor will be overwritten by those set in `globalSceneOptions`.
* @param {(number|function)} [options.duration=0] - The duration of the scene.
If `0` tweens will auto-play when reaching the scene start point, pins will be pinned indefinetly starting at the start position.
A function retuning the duration value is also supported. Please see `Scene.duration()` for details.
* @param {number} [options.offset=0] - Offset Value for the Trigger Position. If no triggerElement is defined this will be the scroll distance from the start of the page, after which the scene will start.
* @param {(string|object)} [options.triggerElement=null] - Selector or DOM object that defines the start of the scene. If undefined the scene will start right at the start of the page (unless an offset is set).
* @param {(number|string)} [options.triggerHook="onCenter"] - Can be a number between 0 and 1 defining the position of the trigger Hook in relation to the viewport.
Can also be defined using a string:
** `"onEnter"` => `1`
** `"onCenter"` => `0.5`
** `"onLeave"` => `0`
* @param {boolean} [options.reverse=true] - Should the scene reverse, when scrolling up?
* @param {number} [options.loglevel=2] - Loglevel for debugging. Note that logging is disabled in the minified version of ScrollMagic.
** `0` => silent
** `1` => errors
** `2` => errors, warnings
** `3` => errors, warnings, debuginfo
*
*/
ScrollMagic.Scene = function (options) {
/*
* ----------------------------------------------------------------
* settings
* ----------------------------------------------------------------
*/
var
NAMESPACE = "ScrollMagic.Scene",
DEFAULT_OPTIONS = SCENE_OPTIONS.defaults;
/*
* ----------------------------------------------------------------
* private vars
* ----------------------------------------------------------------
*/
var
Scene = this,
_options = _util.extend({}, DEFAULT_OPTIONS, options),
_state = 'BEFORE',
_progress = 0,
_scrollOffset = {
start: 0,
end: 0
},
// reflects the controllers's scroll position for the start and end of the scene respectively
_triggerPos = 0,
_enabled = true,
_durationUpdateMethod, _controller;
/**
* Internal constructor function of the ScrollMagic Scene
* @private
*/
var construct = function () {
for (var key in _options) { // check supplied options
if (!DEFAULT_OPTIONS.hasOwnProperty(key)) {
log(2, "WARNING: Unknown option \"" + key + "\"");
delete _options[key];
}
}
// add getters/setters for all possible options
for (var optionName in DEFAULT_OPTIONS) {
addSceneOption(optionName);
}
// validate all options
validateOption();
// set event listeners
Scene.on("change.internal", function (e) {
if (e.what !== "loglevel" && e.what !== "tweenChanges") { // no need for a scene update scene with these options...
if (e.what === "triggerElement") {
updateTriggerElementPosition();
} else if (e.what === "reverse") { // the only property left that may have an impact on the current scene state. Everything else is handled by the shift event.
Scene.update();
}
}
}).on("shift.internal", function (e) {
updateScrollOffset();
Scene.update(); // update scene to reflect new position
});
};
/**
* Send a debug message to the console.
* @private
* but provided publicly with _log for plugins
*
* @param {number} loglevel - The loglevel required to initiate output for the message.
* @param {...mixed} output - One or more variables that should be passed to the console.
*/
var log = this._log = function (loglevel, output) {
if (_options.loglevel >= loglevel) {
Array.prototype.splice.call(arguments, 1, 0, "(" + NAMESPACE + ") ->");
_util.log.apply(window, arguments);
}
};
/**
* Add the scene to a controller.
* This is the equivalent to `Controller.addScene(scene)`.
* @method ScrollMagic.Scene#addTo
*
* @example
* // add a scene to a ScrollMagic Controller
* scene.addTo(controller);
*
* @param {ScrollMagic.Controller} controller - The controller to which the scene should be added.
* @returns {Scene} Parent object for chaining.
*/
this.addTo = function (controller) {
if (!(controller instanceof ScrollMagic.Controller)) {
log(1, "ERROR: supplied argument of 'addTo()' is not a valid ScrollMagic Controller");
} else if (_controller != controller) {
// new controller
if (_controller) { // was associated to a different controller before, so remove it...
_controller.removeScene(Scene);
}
_controller = controller;
validateOption();
updateDuration(true);
updateTriggerElementPosition(true);
updateScrollOffset();
_controller.info("container").addEventListener('resize', onContainerResize);
controller.addScene(Scene);
Scene.trigger("add", {
controller: _controller
});
log(3, "added " + NAMESPACE + " to controller");
Scene.update();
}
return Scene;
};
/**
* **Get** or **Set** the current enabled state of the scene.
* This can be used to disable this scene without removing or destroying it.
* @method ScrollMagic.Scene#enabled
*
* @example
* // get the current value
* var enabled = scene.enabled();
*
* // disable the scene
* scene.enabled(false);
*
* @param {boolean} [newState] - The new enabled state of the scene `true` or `false`.
* @returns {(boolean|Scene)} Current enabled state or parent object for chaining.
*/
this.enabled = function (newState) {
if (!arguments.length) { // get
return _enabled;
} else if (_enabled != newState) { // set
_enabled = !! newState;
Scene.update(true);
}
return Scene;
};
/**
* Remove the scene from the controller.
* This is the equivalent to `Controller.removeScene(scene)`.
* The scene will not be updated anymore until you readd it to a controller.
* To remove the pin or the tween you need to call removeTween() or removePin() respectively.
* @method ScrollMagic.Scene#remove
* @example
* // remove the scene from its controller
* scene.remove();
*
* @returns {Scene} Parent object for chaining.
*/
this.remove = function () {
if (_controller) {
_controller.info("container").removeEventListener('resize', onContainerResize);
var tmpParent = _controller;
_controller = undefined;
tmpParent.removeScene(Scene);
Scene.trigger("remove");
log(3, "removed " + NAMESPACE + " from controller");
}
return Scene;
};
/**
* Destroy the scene and everything.
* @method ScrollMagic.Scene#destroy
* @example
* // destroy the scene without resetting the pin and tween to their initial positions
* scene = scene.destroy();
*
* // destroy the scene and reset the pin and tween
* scene = scene.destroy(true);
*
* @param {boolean} [reset=false] - If `true` the pin and tween (if existent) will be reset.
* @returns {null} Null to unset handler variables.
*/
this.destroy = function (reset) {
Scene.trigger("destroy", {
reset: reset
});
Scene.remove();
Scene.off("*.*");
log(3, "destroyed " + NAMESPACE + " (reset: " + (reset ? "true" : "false") + ")");
return null;
};
/**
* Updates the Scene to reflect the current state.
* This is the equivalent to `Controller.updateScene(scene, immediately)`.
* The update method calculates the scene's start and end position (based on the trigger element, trigger hook, duration and offset) and checks it against the current scroll position of the container.
* It then updates the current scene state accordingly (or does nothing, if the state is already correct) – Pins will be set to their correct position and tweens will be updated to their correct progress.
* This means an update doesn't necessarily result in a progress change. The `progress` event will be fired if the progress has indeed changed between this update and the last.
* _**NOTE:** This method gets called constantly whenever ScrollMagic detects a change. The only application for you is if you change something outside of the realm of ScrollMagic, like moving the trigger or changing tween parameters._
* @method ScrollMagic.Scene#update
* @example
* // update the scene on next tick
* scene.update();
*
* // update the scene immediately
* scene.update(true);
*
* @fires Scene.update
*
* @param {boolean} [immediately=false] - If `true` the update will be instant, if `false` it will wait until next update cycle (better performance).
* @returns {Scene} Parent object for chaining.
*/
this.update = function (immediately) {
if (_controller) {
if (immediately) {
if (_controller.enabled() && _enabled) {
var