1/*! 2 * ScrollMagic v2.0.5 (2015-04-29) 3 * The javascript library for magical scroll interactions. 4 * (c) 2015 Jan Paepke (@janpaepke) 5 * Project Website: http://scrollmagic.io 6 * 7 * @version 2.0.5 8 * @license Dual licensed under MIT license and GPL. 9 * @author Jan Paepke - [email protected] 10 * 11 * @file ScrollMagic main library. 12 */ 13/** 14 * @namespace ScrollMagic 15 */ 16(function (root, factory) { 17 if (typeof define === 'function' && define.amd) { 18 // AMD. Register as an anonymous module. 19 define(factory); 20 } else if (typeof exports === 'object') { 21 // CommonJS 22 module.exports = factory(); 23 } else { 24 // Browser global 25 root.ScrollMagic = factory(); 26 } 27}(this, function () { 28 "use strict"; 29 30 var ScrollMagic = function () { 31 _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.'); 32 }; 33 34 ScrollMagic.version = "2.0.5"; 35 36 // TODO: temporary workaround for chrome's scroll jitter bug 37 window.addEventListener("mousewheel", function () {}); 38 39 // global const 40 var PIN_SPACER_ATTRIBUTE = "data-scrollmagic-pin-spacer"; 41 42 /** 43 * The main class that is needed once per scroll container. 44 * 45 * @class 46 * 47 * @example 48 * // basic initialization 49 * var controller = new ScrollMagic.Controller(); 50 * 51 * // passing options 52 * var controller = new ScrollMagic.Controller({container: "#myContainer", loglevel: 3}); 53 * 54 * @param {object} [options] - An object containing one or more options for the controller. 55 * @param {(string|object)} [options.container=window] - A selector, DOM object that references the main container for scrolling. 56 * @param {boolean} [options.vertical=true] - Sets the scroll mode to vertical (`true`) or horizontal (`false`) scrolling. 57 * @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}. 58 * @param {number} [options.loglevel=2] Loglevel for debugging. Note that logging is disabled in the minified version of ScrollMagic. 59 ** `0` => silent 60 ** `1` => errors 61 ** `2` => errors, warnings 62 ** `3` => errors, warnings, debuginfo 63 * @param {boolean} [options.refreshInterval=100] - Some changes don't call events by default, like changing the container size or moving a scene trigger element. 64 This interval polls these parameters to fire the necessary events. 65 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. 66 * 67 */ 68 ScrollMagic.Controller = function (options) { 69/* 70 * ---------------------------------------------------------------- 71 * settings 72 * ---------------------------------------------------------------- 73 */ 74 var 75 NAMESPACE = 'ScrollMagic.Controller', 76 SCROLL_DIRECTION_FORWARD = 'FORWARD', 77 SCROLL_DIRECTION_REVERSE = 'REVERSE', 78 SCROLL_DIRECTION_PAUSED = 'PAUSED', 79 DEFAULT_OPTIONS = CONTROLLER_OPTIONS.defaults; 80 81/* 82 * ---------------------------------------------------------------- 83 * private vars 84 * ---------------------------------------------------------------- 85 */ 86 var 87 Controller = this, 88 _options = _util.extend({}, DEFAULT_OPTIONS, options), 89 _sceneObjects = [], 90 _updateScenesOnNextCycle = false, 91 // can be boolean (true => all scenes) or an array of scenes to be updated 92 _scrollPos = 0, 93 _scrollDirection = SCROLL_DIRECTION_PAUSED, 94 _isDocument = true, 95 _viewPortSize = 0, 96 _enabled = true, 97 _updateTimeout, _refreshTimeout; 98 99/* 100 * ---------------------------------------------------------------- 101 * private functions 102 * ---------------------------------------------------------------- 103 */ 104 105 /** 106 * Internal constructor function of the ScrollMagic Controller 107 * @private 108 */ 109 var construct = function () { 110 for (var key in _options) { 111 if (!DEFAULT_OPTIONS.hasOwnProperty(key)) { 112 log(2, "WARNING: Unknown option \"" + key + "\""); 113 delete _options[key]; 114 } 115 } 116 _options.container = _util.get.elements(_options.container)[0];
117 // check ScrollContainer 118 if (!_options.container) { 119 log(1, "ERROR creating object " + NAMESPACE + ": No valid scroll container supplied"); 120 throw NAMESPACE + " init failed."; // cancel 121 } 122 _isDocument = _options.container === window || _options.container === document.body || !document.body.contains(_options.container); 123 // normalize to window 124 if (_isDocument) { 125 _options.container = window; 126 } 127 // update container size immediately 128 _viewPortSize = getViewportSize(); 129 // set event handlers 130 _options.container.addEventListener("resize", onChange); 131 _options.container.addEventListener("scroll", onChange); 132 133 _options.refreshInterval = parseInt(_options.refreshInterval) || DEFAULT_OPTIONS.refreshInterval; 134 scheduleRefresh(); 135 136 log(3, "added new " + NAMESPACE + " controller (v" + ScrollMagic.version + ")"); 137 }; 138 139 /** 140 * Schedule the next execution of the refresh function 141 * @private 142 */ 143 var scheduleRefresh = function () { 144 if (_options.refreshInterval > 0) { 145 _refreshTimeout = window.setTimeout(refresh, _options.refreshInterval); 146 } 147 }; 148 149 /** 150 * Default function to get scroll pos - overwriteable using `Controller.scrollPos(newFunction)` 151 * @private 152 */ 153 var getScrollPos = function () { 154 return _options.vertical ? _util.get.scrollTop(_options.container) : _util.get.scrollLeft(_options.container); 155 }; 156 157 /** 158 * Returns the current viewport Size (width vor horizontal, height for vertical) 159 * @private 160 */ 161 var getViewportSize = function () { 162 return _options.vertical ? _util.get.height(_options.container) : _util.get.width(_options.container); 163 }; 164 165 /** 166 * Default function to set scroll pos - overwriteable using `Controller.scrollTo(newFunction)` 167 * Make available publicly for pinned mousewheel workaround. 168 * @private 169 */ 170 var setScrollPos = this._setScrollPos = function (pos) { 171 if (_options.vertical) { 172 if (_isDocument) { 173 window.scrollTo(_util.get.scrollLeft(), pos); 174 } else { 175 _options.container.scrollTop = pos; 176 } 177 } else { 178 if (_isDocument) { 179 window.scrollTo(pos, _util.get.scrollTop()); 180 } else { 181 _options.container.scrollLeft = pos; 182 } 183 } 184 }; 185 186 /** 187 * Handle updates in cycles instead of on scroll (performance) 188 * @private 189 */ 190 var updateScenes = function () { 191 if (_enabled && _updateScenesOnNextCycle) { 192 // determine scenes to update 193 var scenesToUpdate = _util.type.Array(_updateScenesOnNextCycle) ? _updateScenesOnNextCycle : _sceneObjects.slice(0); 194 // reset scenes 195 _updateScenesOnNextCycle = false; 196 var oldScrollPos = _scrollPos; 197 // update scroll pos now instead of onChange, as it might have changed since scheduling (i.e. in-browser smooth scroll) 198 _scrollPos = Controller.scrollPos(); 199 var deltaScroll = _scrollPos - oldScrollPos; 200 if (deltaScroll !== 0) { // scroll position changed? 201 _scrollDirection = (deltaScroll > 0) ? SCROLL_DIRECTION_FORWARD : SCROLL_DIRECTION_REVERSE; 202 } 203 // reverse order of scenes if scrolling reverse 204 if (_scrollDirection === SCROLL_DIRECTION_REVERSE) { 205 scenesToUpdate.reverse(); 206 } 207 // update scenes 208 scenesToUpdate.forEach(function (scene, index) { 209 log(3, "updating Scene " + (index + 1) + "/" + scenesToUpdate.length + " (" + _sceneObjects.length + " total)"); 210 scene.update(true); 211 }); 212 if (scenesToUpdate.length === 0 && _options.loglevel >= 3) { 213 log(3, "updating 0 Scenes (nothing added to controller)"); 214 } 215 } 216 }; 217 218 /** 219 * Initializes rAF callback 220 * @private 221 */ 222 var debounceUpdate = function () { 223 _updateTimeout = _util.rAF(updateScenes); 224 }; 225 226 /** 227 * Handles Container changes 228 * @private 229 */ 230 var onChange = function (e) { 231 log(3, "event fired causing an update:", e.type); 232 if (e.type == "resize") { 233 // resize 234 _viewPortSize = getViewportSize(); 235 _scrollDirection = SCROLL_DIRECTION_PAUSED; 236 } 237 // schedule update 238 if (_updateScenesOnNextCycle !== true) { 239 _updateScenesOnNextCycle = true; 240 debounceUpdate(); 241 } 242 }; 243 244 var refresh = function () { 245 if (!_isDocument) { 246 // simulate resize event. Only works for viewport relevant param (performance) 247 if (_viewPortSize != getViewportSize()) { 248 var resizeEvent; 249 try { 250 resizeEvent = new Event('resize', { 251 bubbles: false, 252 cancelable: false 253 }); 254 } catch (e) { // stupid IE 255 resizeEvent = document.createEvent("Event"); 256 resizeEvent.initEvent("resize", false, false); 257 }
258 _options.container.dispatchEvent(resizeEvent); 259 } 260 } 261 _sceneObjects.forEach(function (scene, index) { // refresh all scenes 262 scene.refresh(); 263 }); 264 scheduleRefresh(); 265 }; 266 267 /** 268 * Send a debug message to the console. 269 * provided publicly with _log for plugins 270 * @private 271 * 272 * @param {number} loglevel - The loglevel required to initiate output for the message. 273 * @param {...mixed} output - One or more variables that should be passed to the console. 274 */ 275 var log = this._log = function (loglevel, output) { 276 if (_options.loglevel >= loglevel) { 277 Array.prototype.splice.call(arguments, 1, 0, "(" + NAMESPACE + ") ->"); 278 _util.log.apply(window, arguments); 279 } 280 }; 281 // 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 282 this._options = _options; 283 284 /** 285 * Sort scenes in ascending order of their start offset. 286 * @private 287 * 288 * @param {array} ScenesArray - an array of ScrollMagic Scenes that should be sorted 289 * @return {array} The sorted array of Scenes. 290 */ 291 var sortScenes = function (ScenesArray) { 292 if (ScenesArray.length <= 1) { 293 return ScenesArray; 294 } else { 295 var scenes = ScenesArray.slice(0); 296 scenes.sort(function (a, b) { 297 return a.scrollOffset() > b.scrollOffset() ? 1 : -1; 298 }); 299 return scenes; 300 } 301 }; 302 303 /** 304 * ---------------------------------------------------------------- 305 * public functions 306 * ---------------------------------------------------------------- 307 */ 308 309 /** 310 * Add one ore more scene(s) to the controller. 311 * This is the equivalent to `Scene.addTo(controller)`. 312 * @public 313 * @example 314 * // with a previously defined scene 315 * controller.addScene(scene); 316 * 317 * // with a newly created scene. 318 * controller.addScene(new ScrollMagic.Scene({duration : 0})); 319 * 320 * // adding multiple scenes 321 * controller.addScene([scene, scene2, new ScrollMagic.Scene({duration : 0})]); 322 * 323 * @param {(ScrollMagic.Scene|array)} newScene - ScrollMagic Scene or Array of Scenes to be added to the controller. 324 * @return {Controller} Parent object for chaining. 325 */ 326 this.addScene = function (newScene) { 327 if (_util.type.Array(newScene)) { 328 newScene.forEach(function (scene, index) { 329 Controller.addScene(scene); 330 }); 331 } else if (newScene instanceof ScrollMagic.Scene) { 332 if (newScene.controller() !== Controller) { 333 newScene.addTo(Controller); 334 } else if (_sceneObjects.indexOf(newScene) < 0) { 335 // new scene 336 _sceneObjects.push(newScene); // add to array 337 _sceneObjects = sortScenes(_sceneObjects); // sort 338 newScene.on("shift.controller_sort", function () { // resort whenever scene moves 339 _sceneObjects = sortScenes(_sceneObjects); 340 }); 341 // insert Global defaults. 342 for (var key in _options.globalSceneOptions) { 343 if (newScene[key]) { 344 newScene[key].call(newScene, _options.globalSceneOptions[key]); 345 } 346 } 347 log(3, "adding Scene (now " + _sceneObjects.length + " total)"); 348 } 349 } else { 350 log(1, "ERROR: invalid argument supplied for '.addScene()'"); 351 } 352 return Controller; 353 }; 354 355 /** 356 * Remove one ore more scene(s) from the controller. 357 * This is the equivalent to `Scene.remove()`. 358 * @public 359 * @example 360 * // remove a scene from the controller 361 * controller.removeScene(scene); 362 * 363 * // remove multiple scenes from the controller 364 * controller.removeScene([scene, scene2, scene3]); 365 * 366 * @param {(ScrollMagic.Scene|array)} Scene - ScrollMagic Scene or Array of Scenes to be removed from the controller. 367 * @returns {Controller} Parent object for chaining. 368 */ 369 this.removeScene = function (Scene) { 370 if (_util.type.Array(Scene)) { 371 Scene.forEach(function (scene, index) { 372 Controller.removeScene(scene); 373 }); 374 } else { 375 var index = _sceneObjects.indexOf(Scene); 376 if (index > -1) { 377 Scene.off("shift.controller_sort"); 378 _sceneObjects.splice(index, 1); 379 log(3, "removing Scene (now " + _sceneObjects.length + " left)"); 380 Scene.remove(); 381 } 382 } 383 return Controller; 384 }; 385 386 /** 387 * Update one ore more scene(s) according to the scroll position of the container.
388 * This is the equivalent to `Scene.update()`. 389 * 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. 390 * 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. 391 * _**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._ 392 * @public 393 * @example 394 * // update a specific scene on next cycle 395 * controller.updateScene(scene); 396 * 397 * // update a specific scene immediately 398 * controller.updateScene(scene, true); 399 * 400 * // update multiple scenes scene on next cycle 401 * controller.updateScene([scene1, scene2, scene3]); 402 * 403 * @param {ScrollMagic.Scene} Scene - ScrollMagic Scene or Array of Scenes that is/are supposed to be updated. 404 * @param {boolean} [immediately=false] - If `true` the update will be instant, if `false` it will wait until next update cycle. 405 This is useful when changing multiple properties of the scene - this way it will only be updated once all new properties are set (updateScenes). 406 * @return {Controller} Parent object for chaining. 407 */ 408 this.updateScene = function (Scene, immediately) { 409 if (_util.type.Array(Scene)) { 410 Scene.forEach(function (scene, index) { 411 Controller.updateScene(scene, immediately); 412 }); 413 } else { 414 if (immediately) { 415 Scene.update(true); 416 } else if (_updateScenesOnNextCycle !== true && Scene instanceof ScrollMagic.Scene) { // if _updateScenesOnNextCycle is true, all connected scenes are already scheduled for update 417 // prep array for next update cycle 418 _updateScenesOnNextCycle = _updateScenesOnNextCycle || []; 419 if (_updateScenesOnNextCycle.indexOf(Scene) == -1) { 420 _updateScenesOnNextCycle.push(Scene); 421 } 422 _updateScenesOnNextCycle = sortScenes(_updateScenesOnNextCycle); // sort 423 debounceUpdate(); 424 } 425 } 426 return Controller; 427 }; 428 429 /** 430 * Updates the controller params and calls updateScene on every scene, that is attached to the controller. 431 * See `Controller.updateScene()` for more information about what this means. 432 * 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. 433 * The only application for this method is when ScrollMagic fails to detect these events. 434 * 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. 435 * 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. 436 * @public 437 * @example 438 * // update the controller on next cycle (saves performance due to elimination of redundant updates) 439 * controller.update(); 440 * 441 * // update the controller immediately 442 * controller.update(true); 443 * 444 * @param {boolean} [immediately=false] - If `true` the update will be instant, if `false` it will wait until next update cycle (better performance) 445 * @return {Controller} Parent object for chaining. 446 */ 447 this.update = function (immediately) { 448 onChange({ 449 type: "resize" 450 }); // will update size and set _updateScenesOnNextCycle to true 451 if (immediately) { 452 updateScenes(); 453 } 454 return Controller; 455 }; 456 457 /** 458 * Scroll to a numeric scroll offset, a DOM element, the start of a scene or provide an alternate method for scrolling. 459 * For vertical controllers it will change the top scroll offset and for horizontal applications it will change the left offset. 460 * @public 461 * 462 * @since 1.1.0 463 * @example 464 * // scroll to an offset of 100 465 * controller.scrollTo(100); 466 * 467 * // scroll to a DOM element 468 * controller.scrollTo("#anchor"); 469 * 470 * // scroll to the beginning of a scene 471 * var scene = new ScrollMagic.Scene({offset: 200}); 472 * controller.scrollTo(scene); 473 * 474 * // define a new scroll position modification function (jQuery animate instead of jump) 475 * controller.scrollTo(function (newScrollPos) { 476 * $("html, body").animate({scrollTop: newScrollPos}); 477 * }); 478 * controller.scrollTo(100); // call as usual, but the new function will be used instead 479 * 480 * // define a new scroll function with an additional parameter 481 * controller.scrollTo(function (newScrollPos, message) { 482 * console.log(message); 483 * $(this).animate({scrollTop: newScrollPos}); 484 * }); 485 * // call as usual, but supply an extra parameter to the defined custom function 486 * controller.scrollTo(100, "my message"); 487 * 488 * // define a new scroll function with an additional parameter containing multiple variables 489 * controller.scrollTo(function (newScrollPos, options) { 490 * someGlobalVar = options.a + options.b; 491 * $(this).animate({scrollTop: newScrollPos}); 492 * }); 493 * // call as usual, but supply an extra parameter containing multiple options 494 * controller.scrollTo(100, {a: 1, b: 2}); 495 * 496 * // define a new scroll function with a callback supplied as an additional parameter 497 * controller.scrollTo(function (newScrollPos, callback) { 498 * $(this).animate({scrollTop: newScrollPos}, 400, "swing", callback); 499 * }); 500 * // call as usual, but supply an extra parameter, which is used as a callback in the previously defined custom scroll function 501 * controller.scrollTo(100, function() { 502 * console.log("scroll has finished."); 503 * }); 504 * 505 * @param {mixed} scrollTarget - The supplied argument can be one of these types: 506 * 1. `number` -> The container will scroll to this new scroll offset. 507 * 2. `string` or `object` -> Can be a selector or a DOM object. 508 * The container will scroll to the position of this element. 509 * 3. `ScrollMagic Scene` -> The container will scroll to the start of this scene. 510 * 4. `function` -> This function will be used for future scroll position modifications. 511 * 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`.
512 * It may also optionally receive an optional additional parameter (see below) 513 * _**NOTE:** 514 * All other options will still work as expected, using the new function to scroll._ 515 * @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. 516 * @returns {Controller} Parent object for chaining. 517 */ 518 this.scrollTo = function (scrollTarget, additionalParameter) { 519 if (_util.type.Number(scrollTarget)) { // excecute 520 setScrollPos.call(_options.container, scrollTarget, additionalParameter); 521 } else if (scrollTarget instanceof ScrollMagic.Scene) { // scroll to scene 522 if (scrollTarget.controller() === Controller) { // check if the controller is associated with this scene 523 Controller.scrollTo(scrollTarget.scrollOffset(), additionalParameter); 524 } else { 525 log(2, "scrollTo(): The supplied scene does not belong to this controller. Scroll cancelled.", scrollTarget); 526 } 527 } else if (_util.type.Function(scrollTarget)) { // assign new scroll function 528 setScrollPos = scrollTarget; 529 } else { // scroll to element 530 var elem = _util.get.elements(scrollTarget)[0]; 531 if (elem) { 532 // if parent is pin spacer, use spacer position instead so correct start position is returned for pinned elements. 533 while (elem.parentNode.hasAttribute(PIN_SPACER_ATTRIBUTE)) { 534 elem = elem.parentNode; 535 } 536 537 var 538 param = _options.vertical ? "top" : "left", 539 // which param is of interest ? 540 containerOffset = _util.get.offset(_options.container), 541 // container position is needed because element offset is returned in relation to document, not in relation to container. 542 elementOffset = _util.get.offset(elem); 543 544 if (!_isDocument) { // container is not the document root, so substract scroll Position to get correct trigger element position relative to scrollcontent 545 containerOffset[param] -= Controller.scrollPos(); 546 } 547 548 Controller.scrollTo(elementOffset[param] - containerOffset[param], additionalParameter); 549 } else { 550 log(2, "scrollTo(): The supplied argument is invalid. Scroll cancelled.", scrollTarget); 551 } 552 } 553 return Controller; 554 }; 555 556 /** 557 * **Get** the current scrollPosition or **Set** a new method to calculate it. 558 * -> **GET**: 559 * When used as a getter this function will return the current scroll position. 560 * To get a cached value use Controller.info("scrollPos"), which will be updated in the update cycle. 561 * For vertical controllers it will return the top scroll offset and for horizontal applications it will return the left offset. 562 * 563 * -> **SET**: 564 * When used as a setter this method prodes a way to permanently overwrite the controller's scroll position calculation. 565 * 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. 566 * Moving a child container inside a parent is a commonly used method for several scrolling frameworks, including iScroll. 567 * By providing an alternate calculation function you can make sure ScrollMagic receives the correct scroll position. 568 * Please also bear in mind that your function should return y values for vertical scrolls an x for horizontals. 569 * 570 * To change the current scroll position please use `Controller.scrollTo()`. 571 * @public 572 * 573 * @example 574 * // get the current scroll Position 575 * var scrollPos = controller.scrollPos(); 576 * 577 * // set a new scroll position calculation method 578 * controller.scrollPos(function () { 579 * return this.info("vertical") ? -mychildcontainer.y : -mychildcontainer.x 580 * }); 581 * 582 * @param {function} [scrollPosMethod] - The function to be used for the scroll position calculation of the container. 583 * @returns {(number|Controller)} Current scroll position or parent object for chaining. 584 */ 585 this.scrollPos = function (scrollPosMethod) { 586 if (!arguments.length) { // get 587 return getScrollPos.call(Controller); 588 } else { // set 589 if (_util.type.Function(scrollPosMethod)) { 590 getScrollPos = scrollPosMethod; 591 } else { 592 log(2, "Provided value for method 'scrollPos' is not a function. To change the current scroll position use 'scrollTo()'."); 593 } 594 } 595 return Controller; 596 }; 597 598 /** 599 * **Get** all infos or one in particular about the controller. 600 * @public 601 * @example 602 * // returns the current scroll position (number) 603 * var scrollPos = controller.info("scrollPos"); 604 * 605 * // returns all infos as an object 606 * var infos = controller.info(); 607 * 608 * @param {string} [about] - If passed only this info will be returned instead of an object c
608ontaining all. 609 Valid options are: 610 ** `"size"` => the current viewport size of the container 611 ** `"vertical"` => true if vertical scrolling, otherwise false 612 ** `"scrollPos"` => the current scroll position 613 ** `"scrollDirection"` => the last known direction of the scroll 614 ** `"container"` => the container element 615 ** `"isDocument"` => true if container element is the document. 616 * @returns {(mixed|object)} The requested info(s). 617 */ 618 this.info = function (about) { 619 var values = { 620 size: _viewPortSize, 621 // contains height or width (in regard to orientation); 622 vertical: _options.vertical, 623 scrollPos: _scrollPos, 624 scrollDirection: _scrollDirection, 625 container: _options.container, 626 isDocument: _isDocument 627 }; 628 if (!arguments.length) { // get all as an object 629 return values; 630 } else if (values[about] !== undefined) { 631 return values[about]; 632 } else { 633 log(1, "ERROR: option \"" + about + "\" is not available"); 634 return; 635 } 636 }; 637 638 /** 639 * **Get** or **Set** the current loglevel option value. 640 * @public 641 * 642 * @example 643 * // get the current value 644 * var loglevel = controller.loglevel(); 645 * 646 * // set a new value 647 * controller.loglevel(3); 648 * 649 * @param {number} [newLoglevel] - The new loglevel setting of the Controller. `[0-3]` 650 * @returns {(number|Controller)} Current loglevel or parent object for chaining. 651 */ 652 this.loglevel = function (newLoglevel) { 653 if (!arguments.length) { // get 654 return _options.loglevel; 655 } else if (_options.loglevel != newLoglevel) { // set 656 _options.loglevel = newLoglevel; 657 } 658 return Controller; 659 }; 660 661 /** 662 * **Get** or **Set** the current enabled state of the controller. 663 * This can be used to disable all Scenes connected to the controller without destroying or removing them. 664 * @public 665 * 666 * @example 667 * // get the current value 668 * var enabled = controller.enabled(); 669 * 670 * // disable the controller 671 * controller.enabled(false); 672 * 673 * @param {boolean} [newState] - The new enabled state of the controller `true` or `false`. 674 * @returns {(boolean|Controller)} Current enabled state or parent object for chaining. 675 */ 676 this.enabled = function (newState) { 677 if (!arguments.length) { // get 678 return _enabled; 679 } else if (_enabled != newState) { // set 680 _enabled = !! newState; 681 Controller.updateScene(_sceneObjects, true); 682 } 683 return Controller; 684 }; 685 686 /** 687 * Destroy the Controller, all Scenes and everything. 688 * @public 689 * 690 * @example 691 * // without resetting the scenes 692 * controller = controller.destroy(); 693 * 694 * // with scene reset 695 * controller = controller.destroy(true); 696 * 697 * @param {boolean} [resetScenes=false] - If `true` the pins and tweens (if existent) of all scenes will be reset. 698 * @returns {null} Null to unset handler variables. 699 */ 700 this.destroy = function (resetScenes) { 701 window.clearTimeout(_refreshTimeout); 702 var i = _sceneObjects.length; 703 while (i--) { 704 _sceneObjects[i].destroy(resetScenes); 705 } 706 _options.container.removeEventListener("resize", onChange); 707 _options.container.removeEventListener("scroll", onChange); 708 _util.cAF(_updateTimeout); 709 log(3, "destroyed " + NAMESPACE + " (reset: " + (resetScenes ? "true" : "false") + ")"); 710 return null; 711 }; 712 713 // INIT 714 construct(); 715 return Controller; 716 }; 717 718 // store pagewide controller options 719 var CONTROLLER_OPTIONS = { 720 defaults: { 721 container: window, 722 vertical: true, 723 globalSceneOptions: {}, 724 loglevel: 2, 725 refreshInterval: 100 726 } 727 }; 728/* 729 * method used to add an option to ScrollMagic Scenes. 730 */ 731 ScrollMagic.Controller.addOption = function (name, defaultValue) { 732 CONTROLLER_OPTIONS.defaults[name] = defaultValue; 733 }; 734 // instance extension function for plugins 735 ScrollMagic.Controller.extend = function (extension) { 736 var oldClass = this; 737 ScrollMagic.Controller = function () { 738 oldClass.apply(this, arguments); 739 this.$super = _util.extend({}, this); // copy parent state 740 return extension.apply(this, arguments) || this; 741 }; 742 _util.extend(ScrollMagic.Controller, oldClass); // copy properties 743 ScrollMagic.Controller.prototype = oldClass.prototype; // copy prototype 744 ScrollMagic.Controller.prototype.constructor = ScrollMagic.Controller; // restore constructor 745 }; 746 747 748 /** 749 * A Scene defines where the controller should react and how. 750 * 751 * @class 752 * 753 * @example 754 * // create a standard scene and add it to a controller 755 * new ScrollMagic.Scene() 756 * .addTo(controller); 757 * 758 * // create a scene with custom options and assign a handler to it. 759 * var scene = new ScrollMagic.Scene({ 760 * duration: 100, 761 * offset: 200, 762 * triggerHook: "onEnter", 763 * reverse: false 764 * }); 765 * 766 * @param {object} [options] - Options for the Scene. The options can be updated at any time. 767 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. 768 When a scene is added to the controller the options defined using the Scene constructor will be overwritten by those set in `globalSceneOptions`. 769 * @param {(number|function)} [options.duration=0] - The duration of the scene. 770 If `0` tweens will auto-play when reaching the scene start point, pins will be pinned indefinetly starting at the start position. 771 A function retuning the duration value is also supported. Please see `Scene.duration()` for details. 772 * @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. 773 * @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). 774 * @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.
775 Can also be defined using a string: 776 ** `"onEnter"` => `1` 777 ** `"onCenter"` => `0.5` 778 ** `"onLeave"` => `0` 779 * @param {boolean} [options.reverse=true] - Should the scene reverse, when scrolling up? 780 * @param {number} [options.loglevel=2] - Loglevel for debugging. Note that logging is disabled in the minified version of ScrollMagic. 781 ** `0` => silent 782 ** `1` => errors 783 ** `2` => errors, warnings 784 ** `3` => errors, warnings, debuginfo 785 * 786 */ 787 ScrollMagic.Scene = function (options) { 788 789/* 790 * ---------------------------------------------------------------- 791 * settings 792 * ---------------------------------------------------------------- 793 */ 794 795 var 796 NAMESPACE = 'ScrollMagic.Scene', 797 SCENE_STATE_BEFORE = 'BEFORE', 798 SCENE_STATE_DURING = 'DURING', 799 SCENE_STATE_AFTER = 'AFTER', 800 DEFAULT_OPTIONS = SCENE_OPTIONS.defaults; 801 802/* 803 * ---------------------------------------------------------------- 804 * private vars 805 * ---------------------------------------------------------------- 806 */ 807 808 var 809 Scene = this, 810 _options = _util.extend({}, DEFAULT_OPTIONS, options), 811 _state = SCENE_STATE_BEFORE, 812 _progress = 0, 813 _scrollOffset = { 814 start: 0, 815 end: 0 816 }, 817 // reflects the controllers's scroll position for the start and end of the scene respectively 818 _triggerPos = 0, 819 _enabled = true, 820 _durationUpdateMethod, _controller; 821 822 /** 823 * Internal constructor function of the ScrollMagic Scene 824 * @private 825 */ 826 var construct = function () { 827 for (var key in _options) { // check supplied options 828 if (!DEFAULT_OPTIONS.hasOwnProperty(key)) { 829 log(2, "WARNING: Unknown option \"" + key + "\""); 830 delete _options[key]; 831 } 832 } 833 // add getters/setters for all possible options 834 for (var optionName in DEFAULT_OPTIONS) { 835 addSceneOption(optionName); 836 } 837 // validate all options 838 validateOption(); 839 }; 840 841/* 842 * ---------------------------------------------------------------- 843 * Event Management 844 * ---------------------------------------------------------------- 845 */ 846 847 var _listeners = {}; 848 /** 849 * Scene start event. 850 * Fires whenever the scroll position its the starting point of the scene. 851 * It will also fire when scrolling back up going over the start position of the scene. If you want something to happen only when scrolling down/right, use the scrollDirection parameter passed to the callback. 852 * 853 * For details on this event and the order in which it is fired, please review the {@link Scene.progress} method. 854 * 855 * @event ScrollMagic.Scene#start 856 * 857 * @example 858 * scene.on("start", function (event) { 859 * console.log("Hit start point of scene."); 860 * }); 861 * 862 * @property {object} event - The event Object passed to each callback 863 * @property {string} event.type - The name of the event 864 * @property {Scene} event.target - The Scene object that triggered this event 865 * @property {number} event.progress - Reflects the current progress of the scene 866 * @property {string} event.state - The current state of the scene `"BEFORE"` or `"DURING"` 867 * @property {string} event.scrollDirection - Indicates which way we are scrolling `"PAUSED"`, `"FORWARD"` or `"REVERSE"` 868 */ 869 /** 870 * Scene end event. 871 * Fires whenever the scroll position its the ending point of the scene. 872 * It will also fire when scrolling back up from after the scene and going over its end position. If you want something to happen only when scrolling down/right, use the scrollDirection parameter passed to the callback. 873 * 874 * For details on this event and the order in which it is fired, please review the {@link Scene.progress} method. 875 * 876 * @event ScrollMagic.Scene#end 877 * 878 * @example 879 * scene.on("end", function (event) { 880 * console.log("Hit end point of scene."); 881 * }); 882 * 883 * @property {object} event - The event Object passed to each callback 884 * @property {string} event.type - The name of the event 885 * @property {Scene} event.target - The Scene object that triggered this event 886 * @property {number} event.progress - Reflects the current progress of the scene 887 * @property {string} event.state - The current state of the scene `"DURING"` or `"AFTER"` 888 * @property {string} event.scrollDirection - Indicates which way we are scrolling `"PAUSED"`, `"FORWARD"` or `"REVERSE"` 889 */ 890 /** 891 * Scene enter event. 892 * Fires whenever the scene enters the "DURING" state. 893 * Keep in mind that it doesn't matter if the scene plays forward or backward: This event al
893ways fires when the scene enters its active scroll timeframe, regardless of the scroll-direction. 894 * 895 * For details on this event and the order in which it is fired, please review the {@link Scene.progress} method. 896 * 897 * @event ScrollMagic.Scene#enter 898 * 899 * @example 900 * scene.on("enter", function (event) { 901 * console.log("Scene entered."); 902 * }); 903 * 904 * @property {object} event - The event Object passed to each callback 905 * @property {string} event.type - The name of the event 906 * @property {Scene} event.target - The Scene object that triggered this event 907 * @property {number} event.progress - Reflects the current progress of the scene 908 * @property {string} event.state - The current state of the scene - always `"DURING"` 909 * @property {string} event.scrollDirection - Indicates which way we are scrolling `"PAUSED"`, `"FORWARD"` or `"REVERSE"` 910 */ 911 /** 912 * Scene leave event. 913 * Fires whenever the scene's state goes from "DURING" to either "BEFORE" or "AFTER". 914 * Keep in mind that it doesn't matter if the scene plays forward or backward: This event always fires when the scene leaves its active scroll timeframe, regardless of the scroll-direction. 915 * 916 * For details on this event and the order in which it is fired, please review the {@link Scene.progress} method. 917 * 918 * @event ScrollMagic.Scene#leave 919 * 920 * @example 921 * scene.on("leave", function (event) { 922 * console.log("Scene left."); 923 * }); 924 * 925 * @property {object} event - The event Object passed to each callback 926 * @property {string} event.type - The name of the event 927 * @property {Scene} event.target - The Scene object that triggered this event 928 * @property {number} event.progress - Reflects the current progress of the scene 929 * @property {string} event.state - The current state of the scene `"BEFORE"` or `"AFTER"` 930 * @property {string} event.scrollDirection - Indicates which way we are scrolling `"PAUSED"`, `"FORWARD"` or `"REVERSE"` 931 */ 932 /** 933 * Scene update event. 934 * Fires whenever the scene is updated (but not necessarily changes the progress). 935 * 936 * @event ScrollMagic.Scene#update 937 * 938 * @example 939 * scene.on("update", function (event) { 940 * console.log("Scene updated."); 941 * }); 942 * 943 * @property {object} event - The event Object passed to each callback 944 * @property {string} event.type - The name of the event 945 * @property {Scene} event.target - The Scene object that triggered this event 946 * @property {number} event.startPos - The starting position of the scene (in relation to the conainer) 947 * @property {number} event.endPos - The ending position of the scene (in relation to the conainer) 948 * @property {number} event.scrollPos - The current scroll position of the container 949 */ 950 /** 951 * Scene progress event. 952 * Fires whenever the progress of the scene changes. 953 * 954 * For details on this event and the order in which it is fired, please review the {@link Scene.progress} method. 955 * 956 * @event ScrollMagic.Scene#progress 957 * 958 * @example 959 * scene.on("progress", function (event) { 960 * console.log("Scene progress changed to " + event.progress); 961 * }); 962 * 963 * @property {object} event - The event Object passed to each callback 964 * @property {string} event.type - The name of the event 965 * @property {Scene} event.target - The Scene object that triggered this event 966 * @property {number} event.progress - Reflects the current progress of the scene 967 * @property {string} event.state - The current state of the scene `"BEFORE"`, `"DURING"` or `"AFTER"` 968 * @property {string} event.scrollDirection - Indicates which way we are scrolling `"PAUSED"`, `"FORWARD"` or `"REVERSE"` 969 */ 970 /** 971 * Scene change event. 972 * Fires whenvever a property of the scene is changed. 973 * 974 * @event ScrollMagic.Scene#change 975 * 976 * @example 977 * scene.on("change", function (event) { 978 * console.log("Scene Property \"" + event.what + "\" changed to " + event.newval); 979 * }); 980 * 981 * @property {object} event - The event Object passed to each callback 982 * @property {string} event.type - The name of the event 983 * @property {Scene} event.target - The Scene object that triggered this event 984 * @property {string} event.what - Indicates what value has been changed 985 * @property {mixed} event.newval - The new value of the changed property 986 */ 987 /** 988 * Scene shift event. 989 * Fires whenvever the start or end **scroll offset** of the scene change. 990 * This happens explicitely, when one of these values change: `offset`, `duration` or `triggerHook`. 991 * It will fire implicitly when the `triggerElement` changes, if the new element has a different position (most cases). 992 * It will also fire implicitly when the size of the container changes and the triggerHook is anything other than `onLeave`. 993 * 994 * @event ScrollMagic.Scene#shift 995 * @since 1.1.0 996 * 997 * @example 998 * scene.on("shift", function (event) { 999 * console.log("Scene moved, because the " + event.reason + " has changed.)"); 1000 * }); 1001 * 1002 * @property {object} event - The event Object passed to each callback 1003 * @property {string} event.type - The name of the event 1004 * @property {Scene} event.target - The Scene object that triggered this event 1005 * @property {string} event.reason - Indicates why the scene has shifted 1006 */ 1007 /** 1008 * Scene destroy event. 1009 * Fires whenvever the scene is destroyed. 1010 * This can be used to tidy up custom behaviour used in events. 1011 * 1012 * @event ScrollMagic.Scene#destroy 1013 * @since 1.1.0 1014 * 1015 * @example 1016 * scene.on("enter", function (event) { 1017 * // add custom action 1018 * $("#my-elem").left("200"); 1019 * }) 1020 * .on("destroy", function (event) { 1021 * // reset my element to start position 1022 * if (event.reset) { 1023 * $("#my-elem").left("0"); 1024 * } 1025 * }); 1026 * 1027 * @property {object} event - The event Object passed to each callback 1028 * @property {string} event.type - The name of the event 1029 * @property {Scene} event.target - The Scene object that triggered this event 1030 * @property {boolean} event.reset - Indicates if the destroy method was called with reset `true` or `false`. 1031 */ 1032 /** 1033 * Scene add event. 1034 * Fires when the scene is added to a controller. 1035 * This is mostly used by plugins to know that change might be due. 1036 * 1037 * @event ScrollMagic.Scene#add 1038 * @since 2.0.0 1039 * 1040 * @example 1041 * scene.on("add", function (event) { 1042 * console.log('Scene was added to a new controller.'); 1043 * }); 1044 * 1045 * @property {object} event - The event Object passed to each callback 1046 * @property {string} event.type - The name of the event 1047 * @property {Scene} event.target - The Scene object that triggered this event 1048 * @property {boolean} event.controller - The controller object the scene was added to. 1049 */ 1050 /** 1051 * Scene remove event. 1052 * Fires when the scene is removed from a controller. 1053 * This is mostly used by plugins to know that change might be due. 1054 * 1055 * @event ScrollMagic.Scene#remove 1056 * @since 2.0.0 1057 * 1058 * @example 1059 * scene.on("remove", function (event) { 1060 * console.log('Scene was removed from its controller.'); 1061 * }); 1062 * 1063 * @property {object} event - The event Object passed to each callback 1064 * @property {string} event.type - The name of the event 1065 * @property {Scene} event.target - The Scene object that triggered this event 1066 */ 1067 1068 /** 1069 * Add one ore more event listener. 1070 * The callback function will be fired at the respective event, and an object c
1070ontaining relevant data will be passed to the callback. 1071 * @method ScrollMagic.Scene#on 1072 * 1073 * @example 1074 * function callback (event) { 1075 * console.log("Event fired! (" + event.type + ")"); 1076 * } 1077 * // add listeners 1078 * scene.on("change update progress start end enter leave", callback); 1079 * 1080 * @param {string} names - The name or names of the event the callback should be attached to. 1081 * @param {function} callback - A function that should be executed, when the event is dispatched. An event object will be passed to the callback. 1082 * @returns {Scene} Parent object for chaining. 1083 */ 1084 this.on = function (names, callback) { 1085 if (_util.type.Function(callback)) { 1086 names = names.trim().split(' '); 1087 names.forEach(function (fullname) { 1088 var 1089 nameparts = fullname.split('.'), 1090 eventname = nameparts[0], 1091 namespace = nameparts[1]; 1092 if (eventname != "*") { // disallow wildcards 1093 if (!_listeners[eventname]) { 1094 _listeners[eventname] = []; 1095 } 1096 _listeners[eventname].push({ 1097 namespace: namespace || '', 1098 callback: callback 1099 }); 1100 } 1101 }); 1102 } else { 1103 log(1, "ERROR when calling '.on()': Supplied callback for '" + names + "' is not a valid function!"); 1104 } 1105 return Scene; 1106 }; 1107 1108 /** 1109 * Remove one or more event listener. 1110 * @method ScrollMagic.Scene#off 1111 * 1112 * @example 1113 * function callback (event) { 1114 * console.log("Event fired! (" + event.type + ")"); 1115 * } 1116 * // add listeners 1117 * scene.on("change update", callback); 1118 * // remove listeners 1119 * scene.off("change update", callback); 1120 * 1121 * @param {string} names - The name or names of the event that should be removed. 1122 * @param {function} [callback] - A specific callback function that should be removed. If none is passed all callbacks to the event listener will be removed. 1123 * @returns {Scene} Parent object for chaining. 1124 */ 1125 this.off = function (names, callback) { 1126 if (!names) { 1127 log(1, "ERROR: Invalid event name supplied."); 1128 return Scene; 1129 } 1130 names = names.trim().split(' '); 1131 names.forEach(function (fullname, key) { 1132 var 1133 nameparts = fullname.split('.'), 1134 eventname = nameparts[0], 1135 namespace = nameparts[1] || '', 1136 removeList = eventname === '*' ? Object.keys(_listeners) : [eventname]; 1137 removeList.forEach(function (remove) { 1138 var 1139 list = _listeners[remove] || [], 1140 i = list.length; 1141 while (i--) { 1142 var listener = list[i]; 1143 if (listener && (namespace === listener.namespace || namespace === '*') && (!callback || callback == listener.callback)) { 1144 list.splice(i, 1); 1145 } 1146 } 1147 if (!list.length) { 1148 delete _listeners[remove]; 1149 } 1150 }); 1151 }); 1152 return Scene; 1153 }; 1154 1155 /** 1156 * Trigger an event. 1157 * @method ScrollMagic.Scene#trigger 1158 * 1159 * @example 1160 * this.trigger("change"); 1161 * 1162 * @param {string} name - The name of the event that should be triggered. 1163 * @param {object} [vars] - An object containing info that should be passed to the callback. 1164 * @returns {Scene} Parent object for chaining. 1165 */ 1166 this.trigger = function (name, vars) { 1167 if (name) { 1168 var 1169 nameparts = name.trim().split('.'), 1170 eventname = nameparts[0], 1171 namespace = nameparts[1], 1172 listeners = _listeners[eventname]; 1173 log(3, 'event fired:', eventname, vars ? "->" : '', vars || ''); 1174 if (listeners) { 1175 listeners.forEach(function (listener, key) { 1176 if (!namespace || namespace === listener.namespace) { 1177 listener.callback.call(Scene, new ScrollMagic.Event(eventname, listener.namespace, Scene, vars)); 1178 } 1179 }); 1180 } 1181 } else { 1182 log(1, "ERROR: Invalid event name supplied."); 1183 } 1184 return Scene; 1185 }; 1186 1187 // set event listeners 1188 Scene.on("change.internal", function (e) { 1189 if (e.what !== "loglevel" && e.what !== "tweenChanges") { // no need for a scene update scene with these options... 1190 if (e.what === "triggerElement") { 1191 updateTriggerElementPosition(); 1192 } 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.
1193 Scene.update(); 1194 } 1195 } 1196 }).on("shift.internal", function (e) { 1197 updateScrollOffset(); 1198 Scene.update(); // update scene to reflect new position 1199 }); 1200 1201 /** 1202 * Send a debug message to the console. 1203 * @private 1204 * but provided publicly with _log for plugins 1205 * 1206 * @param {number} loglevel - The loglevel required to initiate output for the message. 1207 * @param {...mixed} output - One or more variables that should be passed to the console. 1208 */ 1209 var log = this._log = function (loglevel, output) { 1210 if (_options.loglevel >= loglevel) { 1211 Array.prototype.splice.call(arguments, 1, 0, "(" + NAMESPACE + ") ->"); 1212 _util.log.apply(window, arguments); 1213 } 1214 }; 1215 1216 /** 1217 * Add the scene to a controller. 1218 * This is the equivalent to `Controller.addScene(scene)`. 1219 * @method ScrollMagic.Scene#addTo 1220 * 1221 * @example 1222 * // add a scene to a ScrollMagic Controller 1223 * scene.addTo(controller); 1224 * 1225 * @param {ScrollMagic.Controller} controller - The controller to which the scene should be added. 1226 * @returns {Scene} Parent object for chaining. 1227 */ 1228 this.addTo = function (controller) { 1229 if (!(controller instanceof ScrollMagic.Controller)) { 1230 log(1, "ERROR: supplied argument of 'addTo()' is not a valid ScrollMagic Controller"); 1231 } else if (_controller != controller) { 1232 // new controller 1233 if (_controller) { // was associated to a different controller before, so remove it... 1234 _controller.removeScene(Scene); 1235 } 1236 _controller = controller; 1237 validateOption(); 1238 updateDuration(true); 1239 updateTriggerElementPosition(true); 1240 updateScrollOffset(); 1241 _controller.info("container").addEventListener('resize', onContainerResize); 1242 controller.addScene(Scene); 1243 Scene.trigger("add", { 1244 controller: _controller 1245 }); 1246 log(3, "added " + NAMESPACE + " to controller"); 1247 Scene.update(); 1248 } 1249 return Scene; 1250 }; 1251 1252 /** 1253 * **Get** or **Set** the current enabled state of the scene. 1254 * This can be used to disable this scene without removing or destroying it. 1255 * @method ScrollMagic.Scene#enabled 1256 * 1257 * @example 1258 * // get the current value 1259 * var enabled = scene.enabled(); 1260 * 1261 * // disable the scene 1262 * scene.enabled(false); 1263 * 1264 * @param {boolean} [newState] - The new enabled state of the scene `true` or `false`. 1265 * @returns {(boolean|Scene)} Current enabled state or parent object for chaining. 1266 */ 1267 this.enabled = function (newState) { 1268 if (!arguments.length) { // get 1269 return _enabled; 1270 } else if (_enabled != newState) { // set 1271 _enabled = !! newState; 1272 Scene.update(true); 1273 } 1274 return Scene; 1275 }; 1276 1277 /** 1278 * Remove the scene from the controller. 1279 * This is the equivalent to `Controller.removeScene(scene)`. 1280 * The scene will not be updated anymore until you readd it to a controller. 1281 * To remove the pin or the tween you need to call removeTween() or removePin() respectively. 1282 * @method ScrollMagic.Scene#remove 1283 * @example 1284 * // remove the scene from its controller 1285 * scene.remove(); 1286 * 1287 * @returns {Scene} Parent object for chaining. 1288 */ 1289 this.remove = function () { 1290 if (_controller) { 1291 _controller.info("container").removeEventListener('resize', onContainerResize); 1292 var tmpParent = _controller; 1293 _controller = undefined; 1294 tmpParent.removeScene(Scene); 1295 Scene.trigger("remove"); 1296 log(3, "removed " + NAMESPACE + " from controller"); 1297 } 1298 return Scene; 1299 }; 1300 1301 /** 1302 * Destroy the scene and everything. 1303 * @method ScrollMagic.Scene#destroy 1304 * @example 1305 * // destroy the scene without resetting the pin and tween to their initial positions 1306 * scene = scene.destroy(); 1307 * 1308 * // destroy the scene and reset the pin and tween 1309 * scene = scene.destroy(true); 1310 * 1311 * @param {boolean} [reset=false] - If `true` the pin and tween (if existent) will be reset. 1312 * @returns {null} Null to unset handler variables. 1313 */ 1314 this.destroy = function (reset) { 1315 Scene.trigger("destroy", { 1316 reset: reset 1317 }); 1318 Scene.remove(); 1319 Scene.off("*.*"); 1320 log(3, "destroyed " + NAMESPACE + " (reset: " + (reset ? "true" : "false") + ")"); 1321 return null; 1322 }; 1323 1324 1325 /** 1326 * Updates the Scene to reflect the current state. 1327 * This is the equivalent to `Controller.updateScene(scene, immediately)`. 1328 * 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. 1329 * 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. 1330 * 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. 1331 * _**NOTE:** This method gets called constantly whenever ScrollMagic detects a change. The only application for you is
1331if you change something outside of the realm of ScrollMagic, like moving the trigger or changing tween parameters._ 1332 * @method ScrollMagic.Scene#update 1333 * @example 1334 * // update the scene on next tick 1335 * scene.update(); 1336 * 1337 * // update the scene immediately 1338 * scene.update(true); 1339 * 1340 * @fires Scene.update 1341 * 1342 * @param {boolean} [immediately=false] - If `true` the update will be instant, if `false` it will wait until next update cycle (better performance). 1343 * @returns {Scene} Parent object for chaining. 1344 */ 1345 this.update = function (immediately) { 1346 if (_controller) { 1347 if (immediately) { 1348 if (_controller.enabled() && _enabled) { 1349 var 1350 scrollPos = _controller.info("scrollPos"), 1351 newProgress; 1352 1353 if (_options.duration > 0) { 1354 newProgress = (scrollPos - _scrollOffset.start) / (_scrollOffset.end - _scrollOffset.start); 1355 } else { 1356 newProgress = scrollPos >= _scrollOffset.start ? 1 : 0; 1357 } 1358 1359 Scene.trigger("update", { 1360 startPos: _scrollOffset.start, 1361 endPos: _scrollOffset.end, 1362 scrollPos: scrollPos 1363 }); 1364 1365 Scene.progress(newProgress); 1366 } else if (_pin && _state === SCENE_STATE_DURING) { 1367 updatePinState(true); // unpin in position 1368 } 1369 } else { 1370 _controller.updateScene(Scene, false); 1371 } 1372 } 1373 return Scene; 1374 }; 1375 1376 /** 1377 * Updates dynamic scene variables like the trigger element position or the duration. 1378 * This method is automatically called in regular intervals from the controller. See {@link ScrollMagic.Controller} option `refreshInterval`. 1379 * 1380 * You can call it to minimize lag, for example when you intentionally change the position of the triggerElement. 1381 * If you don't it will simply be updated in the next refresh interval of the container, which is usually sufficient. 1382 * 1383 * @method ScrollMagic.Scene#refresh 1384 * @since 1.1.0 1385 * @example 1386 * scene = new ScrollMagic.Scene({triggerElement: "#trigger"}); 1387 * 1388 * // change the position of the trigger 1389 * $("#trigger").css("top", 500); 1390 * // immediately let the scene know of this change 1391 * scene.refresh(); 1392 * 1393 * @fires {@link Scene.shift}, if the trigger element position or the duration changed 1394 * @fires {@link Scene.change}, if the duration changed 1395 * 1396 * @returns {Scene} Parent object for chaining. 1397 */ 1398 this.refresh = function () { 1399 updateDuration(); 1400 updateTriggerElementPosition(); 1401 // update trigger element position 1402 return Scene; 1403 }; 1404 1405 /** 1406 * **Get** or **Set** the scene's progress. 1407 * Usually it shouldn't be necessary to use this as a setter, as it is set automatically by scene.update(). 1408 * The order in which the events are fired depends on the duration of the scene: 1409 * 1. Scenes with `duration == 0`: 1410 * Scenes that have no duration by definition have no ending. Thus the `end` event will never be fired. 1411 * When the trigger position of the scene is passed the events are always fired in this order: 1412 * `enter`, `start`, `progress` when scrolling forward 1413 * and 1414 * `progress`, `start`, `leave` when scrolling in reverse 1415 * 2. Scenes with `duration > 0`: 1416 * Scenes with a set duration have a defined start and end point. 1417 * When scrolling past the start position of the scene it will fire these events in this order: 1418 * `enter`, `start`, `progress` 1419 * When continuing to scroll and passing the end point it will fire these events: 1420 * `progress`, `end`, `leave` 1421 * When reversing through the end point these events are fired: 1422 * `enter`, `end`, `progress` 1423 * And when continuing to scroll past the start position in reverse it will fire: 1424 * `progress`, `start`, `leave` 1425 * In between start and end the `progress` event will be called constantly, whenever the progress changes. 1426 * 1427 * In short: 1428 * `enter` events will always trigger **before** the progress update and `leave` envents will trigger **after** the progress update. 1429 * `start` and `end` will always trigger at their respective position. 1430 * 1431 * Please review the event descriptions for details on the events and the event object that is passed to the callback. 1432 * 1433 * @method ScrollMagic.Scene#progress 1434 * @example 1435 * // get the current scene progress 1436 * var progress = scene.progress(); 1437 * 1438 * // set new scene progress 1439 * scene.progress(0.3); 1440 * 1441 * @fires {@link Scene.enter}, when used as setter 1442 * @fires {@link Scene.start}, when used as setter 1443 * @fires {@link Scene.progress}, when used as setter 1444 * @fires {@link Scene.end}, when used as setter 1445 * @fires {@link Scene.leave}, when used as setter 1446 * 1447 * @param {number} [progress] - The new progress value of the scene `[0-1]`. 1448 * @returns {number} `get` - Current scene progress. 1449 * @returns {Scene} `set` - Parent object for chaining. 1450 */ 1451 this.progress = function (progress) { 1452 if (!arguments.length) { // get 1453 return _progress; 1454 } else { // set 1455 var 1456 doUpdate = false, 1457 oldState = _state, 1458 scrollDirection = _controller ? _controller.info("scrollDirection") : 'PAUSED', 1459 reverseOrForward = _options.reverse || progress >= _progress; 1460 if (_options.duration === 0) { 1461 // zero duration scenes 1462 doUpdate = _progress != progress; 1463 _progress = progress < 1 && reverseOrForward ? 0 : 1; 1464 _state = _progress === 0 ? SCENE_STATE_BEFORE : SCENE_STATE_DURING; 1465 } else { 1466 // scenes with start and end 1467 if (progress < 0 && _state !== SCENE_STATE_BEFORE && reverseOrForward) { 1468 // go back to initial state 1469 _progress = 0; 1470 _state = SCENE_STATE_BEFORE; 1471 doUpdate = true; 1472 } else if (progress >= 0 && progress < 1 && reverseOrForward) { 1473 _progress = progress; 1474 _state = SCENE_STATE_DURING; 1475 doUpdate = true; 1476 } else if (progress >= 1 && _state !== SCENE_STATE_AFTER) { 1477 _progress = 1; 1478 _state = SCENE_STATE_AFTER; 1479 doUpdate = true; 1480 } else if (_state === SCENE_STATE_DURING && !reverseOrForward) { 1481 updatePinState(); // in case we scrolled backwards mid-scene and reverse is disabled => update the pin position, so it doesn't move back as well. 1482 } 1483 } 1484 if (doUpdate) { 1485 // fire events 1486 var 1487 eventVars = { 1488 progress: _progress, 1489 state: _state, 1490 scrollDirection: scrollDirection 1491 }, 1492 stateChanged = _state != oldState; 1493 1494 var trigger = function (eventName) { // tmp helper to simplify code 1495 Scene.trigger(eventName, eventVars); 1496 }; 1497 1498 if (stateChanged) { // enter events 1499 if (oldState !== SCENE_STATE_DURING) { 1500 trigger("enter"); 1501 trigger(oldState === SCENE_STATE_BEFORE ? "start" : "end"); 1502 } 1503 } 1504 trigger("progress"); 1505 if (stateChanged) { // leave events 1506 if (_state !== SCENE_STATE_DURING) { 1507 trigger(_state === SCENE_STATE_BEFORE ? "start" : "end"); 1508 trigger("leave"); 1509 } 1510 } 1511 } 1512 1513 return Scene; 1514 } 1515 }; 1516 1517 1518 /** 1519 * Update the start and end scrollOffset of the container. 1520 * The positions reflect what the controller's scroll position will be at the start and end respectively. 1521 * Is called, when: 1522 * - Scene event "change" is called with: offset, triggerHook, duration 1523 * - scroll container event "resize" is called 1524 * - the position of the triggerElement changes 1525 * - the controller changes -> addTo() 1526 * @private 1527 */ 1528 var updateScrollOffset = function () { 1529 _scrollOffset = { 1530 start: _triggerPos + _options.offset 1531 }; 1532 if (_controller && _options.triggerElement) { 1533 // take away triggerHook portion to get relative to top 1534 _scrollOffset.start -= _controller.info("size") * _options.triggerHook; 1535 } 1536 _scrollOffset.end = _scrollOffset.start + _options.duration; 1537 }; 1538 1539 /** 1540 * Updates the duration if set to a dynamic function. 1541 * This method is called when the scene is added to a controller and in regular intervals from the controller through scene.refresh(). 1542 * 1543 * @fires {@link Scene.change}, if the duration changed 1544 * @fires {@link Scene.shift}, if the duration changed 1545 * 1546 * @param {boolean} [suppressEvents=false] - If true the shift event will be suppressed. 1547 * @private 1548 */ 1549 var updateDuration = function (suppressEvents) { 1550 // update duration 1551 if (_durationUpdateMethod) { 1552 var varname = "duration"; 1553 if (changeOption(varname, _durationUpdateMethod.call(Scene)) && !suppressEvents) { // set 1554 Scene.trigger("change", { 1555 what: varname, 1556 newval: _options[varname] 1557 }); 1558 Scene.trigger("shift", { 1559 reason: varname 1560 }); 1561 } 1562 } 1563 }; 1564 1565 /** 1566 * Updates the position of the triggerElement, if present. 1567 * This method is called ... 1568 * - ... when the triggerElement is changed 1569 * - ... when the scene is added to a (new) controller 1570 * - ... in regular intervals from the controller through scene.refresh(). 1571 * 1572 * @fires {@link Scene.shift}, if the position changed 1573 * 1574 * @param {boolean} [suppressEvents=false] - If true the shift event will be suppressed. 1575 * @private 1576 */ 1577 var updateTriggerElementPosition = function (suppressEvents) { 1578 var 1579 elementPos = 0, 1580 telem = _options.triggerElement; 1581 if (_controller && telem) { 1582 var 1583 controllerInfo = _controller.info(), 1584 containerOffset = _util.get.offset(controllerInfo.container), 1585 // container position is needed because element offset is returned in relation to document, not in relation to container. 1586 param = controllerInfo.vertical ? "top" : "left"; // which param is of interest ? 1587 // if parent is spacer, use spacer position instead so correct start position is returned for pinned elements. 1588 while (telem.parentNode.hasAttribute(PIN_SPACER_ATTRIBUTE)) { 1589 telem = telem.parentNode; 1590 } 1591 1592 var elementOffset = _util.get.offset(telem); 1593 1594 if (!controllerInfo.isDocument) { // container is not the document root, so substract scroll Position to get correct trigger element position relative to scrollcontent 1595 containerOffset[param] -= _controller.scrollPos(); 1596 } 1597 1598 elementPos = elementOffset[param] - containerOffset[param]; 1599 } 1600 var changed = elementPos != _triggerPos; 1601 _triggerPos = elementPos; 1602 if (changed && !suppressEvents) { 1603 Scene.trigger("shift", { 1604 reason: "triggerElementPosition" 1605 }); 1606 } 1607 }; 1608 1609 /** 1610 * Trigger a shift event, when the container is resized and the triggerHook is > 1. 1611 * @private 1612 */ 1613 var onContainerResize = function (e) { 1614 if (_options.triggerHook > 0) { 1615 Scene.trigger("shift", { 1616 reason: "containerResize" 1617 }); 1618 } 1619 }; 1620 1621 var _validate = _util.extend(SCENE_OPTIONS.validate, { 1622 // validation for duration handled internally for reference to private var _durationMethod 1623 duration: function (val) { 1624 if (_util.type.String(val) && val.match(/^(\.|\d)*\d+%$/)) { 1625 // percentage value 1626 var perc = parseFloat(val) / 100; 1627 val = function () { 1628 return _controller ? _controller.info("size") * perc : 0; 1629 }; 1630 } 1631 if (_util.type.Function(val)) { 1632 // function 1633 _durationUpdateMethod = val; 1634 try { 1635 val = parseFloat(_durationUpdateMethod()); 1636 } catch (e) { 1637 val = -1; // will cause error below 1638 } 1639 } 1640 // val has to be float 1641 val = parseFloat(val); 1642 if (!_util.type.Number(val) || val < 0) { 1643 if (_durationUpdateMethod) { 1644 _durationUpdateMethod = undefined; 1645 throw ["Invalid return value of supplied function for option \"duration\":", val]; 1646 } else { 1647 throw ["Invalid value for option \"duration\":", val]; 1648 } 1649 } 1650 return val; 1651 } 1652 }); 1653 1654 /** 1655 * Checks the validity of a specific or all options and reset to default if neccessary. 1656 * @private 1657 */
1658 var validateOption = function (check) { 1659 check = arguments.length ? [check] : Object.keys(_validate); 1660 check.forEach(function (optionName, key) { 1661 var value; 1662 if (_validate[optionName]) { // there is a validation method for this option 1663 try { // validate value 1664 value = _validate[optionName](_options[optionName]); 1665 } catch (e) { // validation failed -> reset to default 1666 value = DEFAULT_OPTIONS[optionName]; 1667 var logMSG = _util.type.String(e) ? [e] : e; 1668 if (_util.type.Array(logMSG)) { 1669 logMSG[0] = "ERROR: " + logMSG[0]; 1670 logMSG.unshift(1); // loglevel 1 for error msg 1671 log.apply(this, logMSG); 1672 } else { 1673 log(1, "ERROR: Problem executing validation callback for option '" + optionName + "':", e.message); 1674 } 1675 } finally { 1676 _options[optionName] = value; 1677 } 1678 } 1679 }); 1680 }; 1681 1682 /** 1683 * Helper used by the setter/getters for scene options 1684 * @private 1685 */ 1686 var changeOption = function (varname, newval) { 1687 var 1688 changed = false, 1689 oldval = _options[varname]; 1690 if (_options[varname] != newval) { 1691 _options[varname] = newval; 1692 validateOption(varname); // resets to default if necessary 1693 changed = oldval != _options[varname]; 1694 } 1695 return changed; 1696 }; 1697 1698 // generate getters/setters for all options 1699 var addSceneOption = function (optionName) { 1700 if (!Scene[optionName]) { 1701 Scene[optionName] = function (newVal) { 1702 if (!arguments.length) { // get 1703 return _options[optionName]; 1704 } else { 1705 if (optionName === "duration") { // new duration is set, so any previously set function must be unset 1706 _durationUpdateMethod = undefined; 1707 } 1708 if (changeOption(optionName, newVal)) { // set 1709 Scene.trigger("change", { 1710 what: optionName, 1711 newval: _options[optionName] 1712 }); 1713 if (SCENE_OPTIONS.shifts.indexOf(optionName) > -1) { 1714 Scene.trigger("shift", { 1715 reason: optionName 1716 }); 1717 } 1718 } 1719 } 1720 return Scene; 1721 }; 1722 } 1723 }; 1724 1725 /** 1726 * **Get** or **Set** the duration option value. 1727 * As a setter it also accepts a function returning a numeric value. 1728 * This is particularly useful for responsive setups. 1729 * 1730 * The duration is updated using the supplied function every time `Scene.refresh()` is called, which happens periodically from the controller (see ScrollMagic.Controller option `refreshInterval`). 1731 * _**NOTE:** Be aware that it's an easy way to kill performance, if you supply a function that has high CPU demand. 1732 * Even for size and position calculations it is recommended to use a variable to cache the value. (see example) 1733 * This counts double if you use the same function for multiple scenes._ 1734 * 1735 * @method ScrollMagic.Scene#duration 1736 * @example 1737 * // get the current duration value 1738 * var duration = scene.duration(); 1739 * 1740 * // set a new duration 1741 * scene.duration(300); 1742 * 1743 * // use a function to automatically adjust the duration to the window height. 1744 * var durationValueCache; 1745 * function getDuration () { 1746 * return durationValueCache; 1747 * } 1748 * function updateDuration (e) { 1749 * durationValueCache = window.innerHeight; 1750 * } 1751 * $(window).on("resize", updateDuration); // update the duration when the window size changes 1752 * $(window).triggerHandler("resize"); // set to initial value 1753 * scene.duration(getDuration); // supply duration method 1754 * 1755 * @fires {@link Scene.change}, when used as setter 1756 * @fires {@link Scene.shift}, when used as setter 1757 * @param {(number|function)} [newDuration] - The new duration of the scene. 1758 * @returns {number} `get` - Current scene duration. 1759 * @returns {Scene} `set` - Parent object for chaining. 1760 */ 1761 1762 /** 1763 * **Get** or **Set** the offset option value. 1764 * @method ScrollMagic.Scene#offset 1765 * @example 1766 * // get the current offset 1767 * var offset = scene.offset(); 1768 * 1769 * // set a new offset 1770 * scene.offset(100); 1771 * 1772 * @fires {@link Scene.change}, when used as setter 1773 * @fires {@link Scene.shift}, when used as setter 1774 * @param {number} [newOffset] - The new offset of the scene. 1775 * @returns {number} `get` - Current scene offset. 1776 * @returns {Scene} `set` - Parent object for chaining. 1777 */ 1778 1779 /** 1780 * **Get** or **Set** the triggerElement option value. 1781 * Does **not** fire `Scene.shift`, because changing the trigger Element doesn't necessarily mean the start position changes. This will be determined in `Scene.refresh()`, which is automatically triggered. 1782 * @method ScrollMagic.Scene#triggerElement 1783 * @example 1784 * // get the current triggerElement 1785 * var triggerElement = scene.triggerElement(); 1786 * 1787 * // set a new triggerElement using a selector 1788 * scene.triggerElement("#trigger"); 1789 * // set a new triggerElement using a DOM object 1790 * scene.triggerElement(document.getElementById("trigger")); 1791 * 1792 * @fires {@link Scene.change}, when used as setter 1793 * @param {(string|object)} [newTriggerElement] - The new trigger element for the scene. 1794 * @returns {(string|object)} `get` - Current triggerElement. 1795 * @returns {Scene} `set` - Parent object for chaining. 1796 */ 1797 1798 /** 1799 * **Get** or **Set** the triggerHook option value. 1800 * @method ScrollMagic.Scene#triggerHook 1801 * @example 1802 * // get the current triggerHook value 1803 * var triggerHook = scene.triggerHook(); 1804 * 1805 * // set a new triggerHook using a string 1806 * scene.triggerHook("onLeave"); 1807 * // set a new triggerHook using a number 1808 * scene.triggerHook(0.7); 1809 * 1810 * @fires {@link Scene.change}, when used as setter 1811 * @fires {@link Scene.shift}, when used as setter 1812 * @param {(number|string)} [newTriggerHook] - The new triggerHook of the scene. See {@link Scene} parameter description for value options. 1813 * @returns {number} `get` - Current triggerHook (ALWAYS numerical). 1814 * @returns {Scene} `set` - Parent object for chaining. 1815 */ 1816 1817 /** 1818 * **Get** or **Set** the reverse option value. 1819 * @method ScrollMagic.Scene#reverse 1820 * @example 1821 * // get the current reverse option 1822 * var reverse = scene.reverse(); 1823 * 1824 * // set new reverse option 1825 * scene.reverse(false); 1826 * 1827 * @fires {@link Scene.change}, when used as setter 1828 * @param {boolean} [newReverse] - The new reverse setting of the scene. 1829 * @returns {boolean} `get` - Current reverse option value. 1830 * @returns {Scene} `set` - Parent object for chaining. 1831 */ 1832 1833 /** 1834 * **Get** or **Set** the loglevel option value. 1835 * @method ScrollMagic.Scene#loglevel 1836 * @example 1837 * // get the current loglevel 1838 * var loglevel = scene.loglevel(); 1839 * 1840 * // set new loglevel 1841 * scene.loglevel(3); 1842 * 1843 * @fires {@link Scene.change}, when used as setter 1844 * @param {number} [newLoglevel] - The new loglevel setting of the scene. `[0-3]` 1845 * @returns {number} `get` - Current loglevel. 1846 * @returns {Scene} `set` - Parent object for chaining. 1847 */ 1848 1849 /** 1850 * **Get** the associated controller. 1851 * @method ScrollMagic.Scene#controller 1852 * @example 1853 * // get the controller of a scene 1854 * var controller = scene.controller(); 1855 * 1856 * @returns {ScrollMagic.Controller} Parent controller or `undefined` 1857 */ 1858 this.controller = function () { 1859 return _controller; 1860 }; 1861 1862 /** 1863 * **Get** the current state. 1864 * @method ScrollMagic.Scene#state 1865 * @example 1866 * // get the current state 1867 * var state = scene.state(); 1868 * 1869 * @returns {string} `"BEFORE"`, `"DURING"` or `"AFTER"` 1870 */ 1871 this.state = function () { 1872 return _state; 1873 }; 1874 1875 /** 1876 * **Get** the current scroll offset for the start of the scene. 1877 * Mind, that the scrollOffset is related to the size of the container, if `triggerHook` is bigger than `0` (or `"onLeave"`). 1878 * This means, that resizing the container or changing the `triggerHook` will influence the scene's start offset. 1879 * @method ScrollMagic.Scene#scrollOffset 1880 * @example 1881 * // get the current scroll offset for the start and end of the scene. 1882 * var start = scene.scrollOffset(); 1883 * var end = scene.scrollOffset() + scene.duration(); 1884 * console.log("the scene starts at", start, "and ends at", end); 1885 * 1886 * @returns {number} The scroll offset (of the container) at which the scene will trigger. Y value for vertical and X value for horizontal scrolls. 1887 */ 1888 this.scrollOffset = function () { 1889 return _scrollOffset.start; 1890 }; 1891 1892 /** 1893 * **Get** the trigger position of the scene (including the value of the `offset` option). 1894 * @method ScrollMagic.Scene#triggerPosition 1895 * @example 1896 * // get the scene's trigger position 1897 * var triggerPosition = scene.triggerPosition(); 1898 * 1899 * @returns {number} Start position of the scene. Top position value for vertical and left position value for horizontal scrolls. 1900 */ 1901 this.triggerPosition = function () { 1902 var pos = _options.offset; // the offset is the basis 1903 if (_controller) { 1904 // get the trigger position 1905 if (_options.triggerElement) { 1906 // Element as trigger 1907 pos += _triggerPos; 1908 } else { 1909 // return the height of the triggerHook to start at the beginning 1910 pos += _controller.info("size") * Scene.triggerHook(); 1911 } 1912 } 1913 return pos; 1914 }; 1915 1916 var
1917 _pin, _pinOptions; 1918 1919 Scene.on("shift.internal", function (e) { 1920 var durationChanged = e.reason === "duration"; 1921 if ((_state === SCENE_STATE_AFTER && durationChanged) || (_state === SCENE_STATE_DURING && _options.duration === 0)) { 1922 // if [duration changed after a scene (inside scene progress updates pin position)] or [duration is 0, we are in pin phase and some other value changed]. 1923 updatePinState(); 1924 } 1925 if (durationChanged) { 1926 updatePinDimensions(); 1927 } 1928 }).on("progress.internal", function (e) { 1929 updatePinState(); 1930 }).on("add.internal", function (e) { 1931 updatePinDimensions(); 1932 }).on("destroy.internal", function (e) { 1933 Scene.removePin(e.reset); 1934 }); 1935 /** 1936 * Update the pin state. 1937 * @private 1938 */ 1939 var updatePinState = function (forceUnpin) { 1940 if (_pin && _controller) { 1941 var 1942 containerInfo = _controller.info(), 1943 pinTarget = _pinOptions.spacer.firstChild; // may be pin element or another spacer, if cascading pins 1944 if (!forceUnpin && _state === SCENE_STATE_DURING) { // during scene or if duration is 0 and we are past the trigger 1945 // pinned state 1946 if (_util.css(pinTarget, "position") != "fixed") { 1947 // change state before updating pin spacer (position changes due to fixed collapsing might occur.) 1948 _util.css(pinTarget, { 1949 "position": "fixed" 1950 }); 1951 // update pin spacer 1952 updatePinDimensions(); 1953 } 1954 1955 var 1956 fixedPos = _util.get.offset(_pinOptions.spacer, true), 1957 // get viewport position of spacer 1958 scrollDistance = _options.reverse || _options.duration === 0 ? containerInfo.scrollPos - _scrollOffset.start // quicker 1959 : Math.round(_progress * _options.duration * 10) / 10; // if no reverse and during pin the position needs to be recalculated using the progress 1960 // add scrollDistance 1961 fixedPos[containerInfo.vertical ? "top" : "left"] += scrollDistance; 1962 1963 // set new values 1964 _util.css(_pinOptions.spacer.firstChild, { 1965 top: fixedPos.top, 1966 left: fixedPos.left 1967 }); 1968 } else { 1969 // unpinned state 1970 var 1971 newCSS = { 1972 position: _pinOptions.inFlow ? "relative" : "absolute", 1973 top: 0, 1974 left: 0 1975 }, 1976 change = _util.css(pinTarget, "position") != newCSS.position; 1977 1978 if (!_pinOptions.pushFollowers) { 1979 newCSS[containerInfo.vertical ? "top" : "left"] = _options.duration * _progress; 1980 } else if (_options.duration > 0) { // only concerns scenes with duration 1981 if (_state === SCENE_STATE_AFTER && parseFloat(_util.css(_pinOptions.spacer, "padding-top")) === 0) { 1982 change = true; // if in after state but havent updated spacer yet (jumped past pin) 1983 } else if (_state === SCENE_STATE_BEFORE && parseFloat(_util.css(_pinOptions.spacer, "padding-bottom")) === 0) { // before 1984 change = true; // jumped past fixed state upward direction 1985 } 1986 } 1987 // set new values 1988 _util.css(pinTarget, newCSS); 1989 if (change) { 1990 // update pin spacer if state changed 1991 updatePinDimensions(); 1992 } 1993 } 1994 } 1995 }; 1996 1997 /** 1998 * Update the pin spacer and/or element size. 1999 * The size of the spacer needs to be updated whenever the duration of the scene changes, if it is to push down following elements. 2000 * @private 2001 */ 2002 var updatePinDimensions = function () { 2003 if (_pin && _controller && _pinOptions.inFlow) { // no spacerresize, if original position is absolute 2004 var 2005 after = (_state === SCENE_STATE_AFTER), 2006 before = (_state === SCENE_STATE_BEFORE), 2007 during = (_state === SCENE_STATE_DURING), 2008 vertical = _controller.info("vertical"), 2009 pinTarget = _pinOptions.spacer.firstChild, 2010 // usually the pined element but can also be another spacer (cascaded pins) 2011 marginCollapse = _util.isMarginCollapseType(_util.css(_pinOptions.spacer, "display")), 2012 css = {}; 2013 2014 // set new size 2015 // if relsize: spacer -> pin | else: pin -> spacer 2016 if (_pinOptions.relSize.width || _pinOptions.relSize.autoFullWidth) { 2017 if (during) { 2018 _util.css(_pin, { 2019 "width": _util.get.width(_pinOptions.spacer) 2020 }); 2021 } else { 2022 _util.css(_pin, { 2023 "width": "100%" 2024 }); 2025 } 2026 } else { 2027 // minwidth is needed for cascaded pins. 2028 css["min-width"] = _util.get.width(vertical ? _pin : pinTarget, true, true); 2029 css.width = during ? css["min-width"] : "auto"; 2030 } 2031 if (_pinOptions.relSize.height) { 2032 if (during) { 2033 // the only padding the spacer should ever include is the duration (if pushFollowers = true), so we need to substract that. 2034 _util.css(_pin, { 2035 "height": _util.get.height(_pinOptions.spacer) - (_pinOptions.pushFollowers ? _options.duration : 0) 2036 }); 2037 } else { 2038 _util.css(_pin, { 2039 "height": "100%" 2040 }); 2041 } 2042 } else { 2043 // margin is only included if it's a cascaded pin to resolve an IE9 bug 2044 css["min-height"] = _util.get.height(vertical ? pinTarget : _pin, true, !marginCollapse); // needed for cascading pins 2045 css.height = during ? css["min-height"] : "auto"; 2046 } 2047 2048 // add space for duration if pushFollowers is true 2049 if (_pinOptions.pushFollowers) { 2050 css["padding" + (vertical ? "Top" : "Left")] = _options.duration * _progress; 2051 css["padding" + (vertical ? "Bottom" : "Right")] = _options.duration * (1 - _progress); 2052 } 2053 _util.css(_pinOptions.spacer, css); 2054 } 2055 }; 2056 2057 /** 2058 * Updates the Pin state (in certain scenarios) 2059 * If the controller container is not the document and we are mid-pin-phase scrolling or resizing the main document can result to wrong pin positions. 2060 * So this function is called on resize and scroll of the document. 2061 * @private 2062 */ 2063 var updatePinInContainer = function () { 2064 if (_controller && _pin && _state === SCENE_STATE_DURING && !_controller.info("isDocument")) { 2065 updatePinState(); 2066 } 2067 }; 2068 2069 /** 2070 * Updates the Pin spacer size state (in certain scenarios) 2071 * If container is resized during pin and relatively sized the size of the pin might need to be updated... 2072 * So this function is called on resize of the container. 2073 * @private 2074 */ 2075 var updateRelativePinSpacer = function () { 2076 if (_controller && _pin && // well, duh 2077 _state === SCENE_STATE_DURING && // element in pinned state? 2078 ( // is width or height relatively sized, but not in relation to body? then we need to recalc. 2079 ((_pinOptions.relSize.width || _pinOptions.relSize.autoFullWidth) && _util.get.width(window) != _util.get.width(_pinOptions.spacer.parentNode)) || (_pinOptions.relSize.height && _util.get.height(window) != _util.get.height(_pinOptions.spacer.parentNode)))) { 2080 updatePinDimensions(); 2081 } 2082 }; 2083 2084 /** 2085 * Is called, when the mousewhel is used while over a pinned element inside a div container. 2086 * If the scene is in fixed state scroll events would be counted towards the body. This forwards the event to the scroll container. 2087 * @private 2088 */ 2089 var onMousewheelOverPin = function (e) { 2090 if (_controller && _pin && _state === SCENE_STATE_DURING && !_controller.info("isDocument")) { // in pin
2090state 2091 e.preventDefault(); 2092 _controller._setScrollPos(_controller.info("scrollPos") - ((e.wheelDelta || e[_controller.info("vertical") ? "wheelDeltaY" : "wheelDeltaX"]) / 3 || -e.detail * 30)); 2093 } 2094 }; 2095 2096 /** 2097 * Pin an element for the duration of the tween. 2098 * If the scene duration is 0 the element will only be unpinned, if the user scrolls back past the start position. 2099 * Make sure only one pin is applied to an element at the same time. 2100 * An element can be pinned multiple times, but only successively. 2101 * _**NOTE:** The option `pushFollowers` has no effect, when the scene duration is 0._ 2102 * @method ScrollMagic.Scene#setPin 2103 * @example 2104 * // pin element and push all following elements down by the amount of the pin duration. 2105 * scene.setPin("#pin"); 2106 * 2107 * // pin element and keeping all following elements in their place. The pinned element will move past them. 2108 * scene.setPin("#pin", {pushFollowers: false}); 2109 * 2110 * @param {(string|object)} element - A Selector targeting an element or a DOM object that is supposed to be pinned. 2111 * @param {object} [settings] - settings for the pin 2112 * @param {boolean} [settings.pushFollowers=true] - If `true` following elements will be "pushed" down for the duration of the pin, if `false` the pinned element will just scroll past them. 2113 Ignored, when duration is `0`. 2114 * @param {string} [settings.spacerClass="scrollmagic-pin-spacer"] - Classname of the pin spacer element, which is used to replace the element. 2115 * 2116 * @returns {Scene} Parent object for chaining. 2117 */ 2118 this.setPin = function (element, settings) { 2119 var 2120 defaultSettings = { 2121 pushFollowers: true, 2122 spacerClass: "scrollmagic-pin-spacer" 2123 }; 2124 settings = _util.extend({}, defaultSettings, settings); 2125 2126 // validate Element 2127 element = _util.get.elements(element)[0]; 2128 if (!element) { 2129 log(1, "ERROR calling method 'setPin()': Invalid pin element supplied."); 2130 return Scene; // cancel 2131 } else if (_util.css(element, "position") === "fixed") { 2132 log(1, "ERROR calling method 'setPin()': Pin does not work with elements that are positioned 'fixed'."); 2133 return Scene; // cancel 2134 } 2135 2136 if (_pin) { // preexisting pin? 2137 if (_pin === element) { 2138 // same pin we already have -> do nothing 2139 return Scene; // cancel 2140 } else { 2141 // kill old pin 2142 Scene.removePin(); 2143 } 2144 2145 } 2146 _pin = element; 2147 2148 var 2149 parentDisplay = _pin.parentNode.style.display, 2150 boundsParams = ["top", "left", "bottom", "right", "margin", "marginLeft", "marginRight", "marginTop", "marginBottom"]; 2151 2152 _pin.parentNode.style.display = 'none'; // hack start to force css to return stylesheet values instead of calculated px values. 2153 var 2154 inFlow = _util.css(_pin, "position") != "absolute", 2155 pinCSS = _util.css(_pin, boundsParams.concat(["display"])), 2156 sizeCSS = _util.css(_pin, ["width", "height"]); 2157 _pin.parentNode.style.display = parentDisplay; // hack end. 2158 if (!inFlow && settings.pushFollowers) { 2159 log(2, "WARNING: If the pinned element is positioned absolutely pushFollowers will be disabled."); 2160 settings.pushFollowers = false; 2161 } 2162 window.setTimeout(function () { // wait until all finished, because with responsive duration it will only be set after scene is added to controller 2163 if (_pin && _options.duration === 0 && settings.pushFollowers) { 2164 log(2, "WARNING: pushFollowers =", true, "has no effect, when scene duration is 0."); 2165 } 2166 }, 0); 2167 2168 // create spacer and insert 2169 var 2170 spacer = _pin.parentNode.insertBefore(document.createElement('div'), _pin), 2171 spacerCSS = _util.extend(pinCSS, { 2172 position: inFlow ? "relative" : "absolute", 2173 boxSizing: "content-box", 2174 mozBoxSizing: "content-box", 2175 webkitBoxSizing: "content-box" 2176 }); 2177 2178 if (!inFlow) { // copy size if positioned absolutely, to work for bottom/right positioned elements. 2179 _util.extend(spacerCSS, _util.css(_pin, ["width", "height"])); 2180 } 2181 2182 _util.css(spacer, spacerCSS); 2183 spacer.setAttribute(PIN_SPACER_ATTRIBUTE, ""); 2184 _util.addClass(spacer, settings.spacerClass); 2185 2186 // set the pin Options 2187 _pinOptions = { 2188 spacer: spacer, 2189 relSize: { // save if size is defined using % values. if so, handle spacer resize differently... 2190 width: sizeCSS.width.slice(-1) === "%", 2191 height: sizeCSS.height.slice(-1) === "%",
2192 autoFullWidth: sizeCSS.width === "auto" && inFlow && _util.isMarginCollapseType(pinCSS.display) 2193 }, 2194 pushFollowers: settings.pushFollowers, 2195 inFlow: inFlow, 2196 // stores if the element takes up space in the document flow 2197 }; 2198 2199 if (!_pin.___origStyle) { 2200 _pin.___origStyle = {}; 2201 var 2202 pinInlineCSS = _pin.style, 2203 copyStyles = boundsParams.concat(["width", "height", "position", "boxSizing", "mozBoxSizing", "webkitBoxSizing"]); 2204 copyStyles.forEach(function (val) { 2205 _pin.___origStyle[val] = pinInlineCSS[val] || ""; 2206 }); 2207 } 2208 2209 // if relative size, transfer it to spacer and make pin calculate it... 2210 if (_pinOptions.relSize.width) { 2211 _util.css(spacer, { 2212 width: sizeCSS.width 2213 }); 2214 } 2215 if (_pinOptions.relSize.height) { 2216 _util.css(spacer, { 2217 height: sizeCSS.height 2218 }); 2219 } 2220 2221 // now place the pin element inside the spacer 2222 spacer.appendChild(_pin); 2223 // and set new css 2224 _util.css(_pin, { 2225 position: inFlow ? "relative" : "absolute", 2226 margin: "auto", 2227 top: "auto", 2228 left: "auto", 2229 bottom: "auto", 2230 right: "auto" 2231 }); 2232 2233 if (_pinOptions.relSize.width || _pinOptions.relSize.autoFullWidth) { 2234 _util.css(_pin, { 2235 boxSizing: "border-box", 2236 mozBoxSizing: "border-box", 2237 webkitBoxSizing: "border-box" 2238 }); 2239 } 2240 2241 // add listener to document to update pin position in case controller is not the document. 2242 window.addEventListener('scroll', updatePinInContainer); 2243 window.addEventListener('resize', updatePinInContainer); 2244 window.addEventListener('resize', updateRelativePinSpacer); 2245 // add mousewheel listener to catch scrolls over fixed elements 2246 _pin.addEventListener("mousewheel", onMousewheelOverPin); 2247 _pin.addEventListener("DOMMouseScroll", onMousewheelOverPin); 2248 2249 log(3, "added pin"); 2250 2251 // finally update the pin to init 2252 updatePinState(); 2253 2254 return Scene; 2255 }; 2256 2257 /** 2258 * Remove the pin from the scene. 2259 * @method ScrollMagic.Scene#removePin 2260 * @example 2261 * // remove the pin from the scene without resetting it (the spacer is not removed) 2262 * scene.removePin(); 2263 * 2264 * // remove the pin from the scene and reset the pin element to its initial position (spacer is removed) 2265 * scene.removePin(true); 2266 * 2267 * @param {boolean} [reset=false] - If `false` the spacer will not be removed and the element's position will not be reset. 2268 * @returns {Scene} Parent object for chaining. 2269 */ 2270 this.removePin = function (reset) { 2271 if (_pin) { 2272 if (_state === SCENE_STATE_DURING) { 2273 updatePinState(true); // force unpin at position 2274 } 2275 if (reset || !_controller) { // if there's no controller no progress was made anyway... 2276 var pinTarget = _pinOptions.spacer.firstChild; // usually the pin element, but may be another spacer (cascaded pins)... 2277 if (pinTarget.hasAttribute(PIN_SPACER_ATTRIBUTE)) { // copy margins to child spacer 2278 var 2279 style = _pinOptions.spacer.style, 2280 values = ["margin", "marginLeft", "marginRight", "marginTop", "marginBottom"]; 2281 margins = {}; 2282 values.forEach(function (val) { 2283 margins[val] = style[val] || ""; 2284 }); 2285 _util.css(pinTarget, margins); 2286 } 2287 _pinOptions.spacer.parentNode.insertBefore(pinTarget, _pinOptions.spacer); 2288 _pinOptions.spacer.parentNode.removeChild(_pinOptions.spacer); 2289 if (!_pin.parentNode.hasAttribute(PIN_SPACER_ATTRIBUTE)) { // if it's the last pin for this element -> restore inline styles 2290 // TODO: only correctly set for first pin (when cascading) - how to fix? 2291 _util.css(_pin, _pin.___origStyle); 2292 delete _pin.___origStyle; 2293 } 2294 } 2295 window.removeEventListener('scroll', updatePinInContainer); 2296 window.removeEventListener('resize', updatePinInContainer); 2297 window.removeEventListener('resize', updateRelativePinSpacer); 2298 _pin.removeEventListener("mousewheel", onMousewheelOverPin); 2299 _pin.removeEventListener("DOMMouseScroll", onMousewheelOverPin); 2300 _pin = undefined; 2301 log(3, "removed pin (reset: " + (reset ? "true" : "false") + ")"); 2302 } 2303 return Scene; 2304 }; 2305 2306 2307 var
2308 _cssClasses, _cssClassElems = []; 2309 2310 Scene.on("destroy.internal", function (e) { 2311 Scene.removeClassToggle(e.reset); 2312 }); 2313 /** 2314 * Define a css class modification while the scene is active. 2315 * When the scene triggers the classes will be added to the supplied element and removed, when the scene is over. 2316 * If the scene duration is 0 the classes will only be removed if the user scrolls back past the start position. 2317 * @method ScrollMagic.Scene#setClassToggle 2318 * @example 2319 * // add the class 'myclass' to the element with the id 'my-elem' for the duration of the scene 2320 * scene.setClassToggle("#my-elem", "myclass"); 2321 * 2322 * // add multiple classes to multiple elements defined by the selector '.classChange' 2323 * scene.setClassToggle(".classChange", "class1 class2 class3"); 2324 * 2325 * @param {(string|object)} element - A Selector targeting one or more elements or a DOM object that is supposed to be modified. 2326 * @param {string} classes - One or more Classnames (separated by space) that should be added to the element during the scene. 2327 * 2328 * @returns {Scene} Parent object for chaining. 2329 */ 2330 this.setClassToggle = function (element, classes) { 2331 var elems = _util.get.elements(element); 2332 if (elems.length === 0 || !_util.type.String(classes)) { 2333 log(1, "ERROR calling method 'setClassToggle()': Invalid " + (elems.length === 0 ? "element" : "classes") + " supplied."); 2334 return Scene; 2335 } 2336 if (_cssClassElems.length > 0) { 2337 // remove old ones 2338 Scene.removeClassToggle(); 2339 } 2340 _cssClasses = classes; 2341 _cssClassElems = elems; 2342 Scene.on("enter.internal_class leave.internal_class", function (e) { 2343 var toggle = e.type === "enter" ? _util.addClass : _util.removeClass; 2344 _cssClassElems.forEach(function (elem, key) {
2345 toggle(elem, _cssClasses); 2346 }); 2347 }); 2348 return Scene; 2349 }; 2350 2351 /** 2352 * Remove the class binding from the scene. 2353 * @method ScrollMagic.Scene#removeClassToggle 2354 * @example 2355 * // remove class binding from the scene without reset 2356 * scene.removeClassToggle(); 2357 * 2358 * // remove class binding and remove the changes it caused 2359 * scene.removeClassToggle(true); 2360 * 2361 * @param {boolean} [reset=false] - If `false` and the classes are currently active, they will remain on the element. If `true` they will be removed. 2362 * @returns {Scene} Parent object for chaining. 2363 */ 2364 this.removeClassToggle = function (reset) { 2365 if (reset) { 2366 _cssClassElems.forEach(function (elem, key) { 2367 _util.removeClass(elem, _cssClasses); 2368 }); 2369 } 2370 Scene.off("start.internal_class end.internal_class"); 2371 _cssClasses = undefined; 2372 _cssClassElems = []; 2373 return Scene; 2374 }; 2375 2376 // INIT 2377 construct(); 2378 return Scene; 2379 }; 2380 2381 // store pagewide scene options 2382 var SCENE_OPTIONS = { 2383 defaults: { 2384 duration: 0, 2385 offset: 0, 2386 triggerElement: undefined, 2387 triggerHook: 0.5, 2388 reverse: true, 2389 loglevel: 2 2390 }, 2391 validate: { 2392 offset: function (val) { 2393 val = parseFloat(val); 2394 if (!_util.type.Number(val)) { 2395 throw ["Invalid value for option \"offset\":", val]; 2396 } 2397 return val; 2398 }, 2399 triggerElement: function (val) { 2400 val = val || undefined; 2401 if (val) { 2402 var elem = _util.get.elements(val)[0]; 2403 if (elem) { 2404 val = elem; 2405 } else { 2406 throw ["Element defined in option \"triggerElement\" was not found:", val]; 2407 } 2408 } 2409 return val; 2410 }, 2411 triggerHook: function (val) { 2412 var translate = { 2413 "onCenter": 0.5, 2414 "onEnter": 1, 2415 "onLeave": 0 2416 }; 2417 if (_util.type.Number(val)) { 2418 val = Math.max(0, Math.min(parseFloat(val), 1)); // make sure its betweeen 0 and 1 2419 } else if (val in translate) { 2420 val = translate[val]; 2421 } else { 2422 throw ["Invalid value for option \"triggerHook\": ", val]; 2423 } 2424 return val; 2425 }, 2426 reverse: function (val) { 2427 return !!val; // force boolean 2428 }, 2429 loglevel: function (val) { 2430 val = parseInt(val); 2431 if (!_util.type.Number(val) || val < 0 || val > 3) { 2432 throw ["Invalid value for option \"loglevel\":", val]; 2433 } 2434 return val; 2435 } 2436 }, 2437 // holder for validation methods. duration validation is handled in 'getters-setters.js' 2438 shifts: ["duration", "offset", "triggerHook"], 2439 // list of options that trigger a `shift` event 2440 }; 2441/* 2442 * method used to add an option to ScrollMagic Scenes. 2443 * TODO: DOC (private for dev) 2444 */ 2445 ScrollMagic.Scene.addOption = function (name, defaultValue, validationCallback, shifts) { 2446 if (!(name in SCENE_OPTIONS.defaults)) { 2447 SCENE_OPTIONS.defaults[name] = defaultValue; 2448 SCENE_OPTIONS.validate[name] = validationCallback; 2449 if (shifts) { 2450 SCENE_OPTIONS.shifts.push(name); 2451 } 2452 } else { 2453 ScrollMagic._util.log(1, "[static] ScrollMagic.Scene -> Cannot add Scene option '" + name + "', because it already exists."); 2454 } 2455 }; 2456 // instance extension function for plugins 2457 // TODO: DOC (private for dev) 2458 ScrollMagic.Scene.extend = function (extension) { 2459 var oldClass = this; 2460 ScrollMagic.Scene = function () { 2461 oldClass.apply(this, arguments); 2462 this.$super = _util.extend({}, this); // copy parent state 2463 return extension.apply(this, arguments) || this; 2464 }; 2465 _util.extend(ScrollMagic.Scene, oldClass); // copy properties 2466 ScrollMagic.Scene.prototype = oldClass.prototype; // copy prototype 2467 ScrollMagic.Scene.prototype.constructor = ScrollMagic.Scene; // restore constructor 2468 }; 2469 2470 2471 /** 2472 * TODO: DOCS (private for dev) 2473 * @class 2474 * @private 2475 */ 2476 2477 ScrollMagic.Event = function (type, namespace, target, vars) { 2478 vars = vars || {}; 2479 for (var key in vars) { 2480 this[key] = vars[key]; 2481 } 2482 this.type = type; 2483 this.target = this.currentTarget = target; 2484 this.namespace = namespace || ''; 2485 this.timeStamp = this.timestamp = Date.now(); 2486 return this; 2487 }; 2488 2489/* 2490 * TODO: DOCS (private for dev) 2491 */ 2492 2493 var _util = ScrollMagic._util = (function (window) { 2494 var U = {}, 2495 i; 2496 2497 /** 2498 * ------------------------------ 2499 * internal helpers 2500 * ------------------------------ 2501 */ 2502 2503 // parse float and fall back to 0. 2504 var floatval = function (number) { 2505 return parseFloat(number) || 0; 2506 }; 2507 // get current style IE safe (otherwise IE would return calculated values for 'auto') 2508 var _getComputedStyle = function (elem) { 2509 return elem.currentStyle ? elem.currentStyle : window.getComputedStyle(elem); 2510 }; 2511 2512 // get element dimension (width or height) 2513 var _dimension = function (which, elem, outer, includeMargin) { 2514 elem = (elem === document) ? window : elem; 2515 if (elem === window) { 2516 includeMargin = false;
2517 } else if (!_type.DomElement(elem)) { 2518 return 0; 2519 } 2520 which = which.charAt(0).toUpperCase() + which.substr(1).toLowerCase(); 2521 var dimension = (outer ? elem['offset' + which] || elem['outer' + which] : elem['client' + which] || elem['inner' + which]) || 0; 2522 if (outer && includeMargin) { 2523 var style = _getComputedStyle(elem); 2524 dimension += which === 'Height' ? floatval(style.marginTop) + floatval(style.marginBottom) : floatval(style.marginLeft) + floatval(style.marginRight); 2525 } 2526 return dimension; 2527 }; 2528 // converts 'margin-top' into 'marginTop' 2529 var _camelCase = function (str) { 2530 return str.replace(/^[^a-z]+([a-z])/g, '$1').replace(/-([a-z])/g, function (g) { 2531 return g[1].toUpperCase(); 2532 }); 2533 }; 2534 2535 /** 2536 * ------------------------------ 2537 * external helpers 2538 * ------------------------------ 2539 */ 2540 2541 // extend obj â same as jQuery.extend({}, objA, objB) 2542 U.extend = function (obj) { 2543 obj = obj || {}; 2544 for (i = 1; i < arguments.length; i++) { 2545 if (!arguments[i]) { 2546 continue; 2547 } 2548 for (var key in arguments[i]) { 2549 if (arguments[i].hasOwnProperty(key)) { 2550 obj[key] = arguments[i][key]; 2551 } 2552 } 2553 } 2554 return obj; 2555 }; 2556 2557 // check if a css display type results in margin-collapse or not 2558 U.isMarginCollapseType = function (str) { 2559 return ["block", "flex", "list-item", "table", "-webkit-box"].indexOf(str) > -1; 2560 }; 2561 2562 // implementation of requestAnimationFrame 2563 // based on https://gist.github.com/paulirish/1579671 2564 var 2565 lastTime = 0, 2566 vendors = ['ms', 'moz', 'webkit', 'o']; 2567 var _requestAnimationFrame = window.requestAnimationFrame; 2568 var _cancelAnimationFrame = window.cancelAnimationFrame; 2569 // try vendor prefixes if the above doesn't work 2570 for (i = 0; !_requestAnimationFrame && i < vendors.length; ++i) { 2571 _requestAnimationFrame = window[vendors[i] + 'RequestAnimationFrame']; 2572 _cancelAnimationFrame = window[vendors[i] + 'CancelAnimationFrame'] || window[vendors[i] + 'CancelRequestAnimationFrame']; 2573 } 2574 2575 // fallbacks 2576 if (!_requestAnimationFrame) { 2577 _requestAnimationFrame = function (callback) { 2578 var 2579 currTime = new Date().getTime(), 2580 timeToCall = Math.max(0, 16 - (currTime - lastTime)), 2581 id = window.setTimeout(function () { 2582 callback(currTime + timeToCall); 2583 }, timeToCall); 2584 lastTime = currTime + timeToCall; 2585 return id; 2586 }; 2587 } 2588 if (!_cancelAnimationFrame) { 2589 _cancelAnimationFrame = function (id) { 2590 window.clearTimeout(id); 2591 }; 2592 } 2593 U.rAF = _requestAnimationFrame.bind(window); 2594 U.cAF = _cancelAnimationFrame.bind(window); 2595 2596 var 2597 loglevels = ["error", "warn", "log"], 2598 console = window.console || {}; 2599 2600 console.log = console.log || 2601 function () {}; // no console log, well - do nothing then... 2602 // make sure methods for all levels exist. 2603 for (i = 0; i < loglevels.length; i++) { 2604 var method = loglevels[i]; 2605 if (!console[method]) { 2606 console[method] = console.log; // prefer .log over nothing 2607 } 2608 } 2609 U.log = function (loglevel) { 2610 if (loglevel > loglevels.length || loglevel <= 0) loglevel = loglevels.length; 2611 var now = new Date(), 2612 time = ("0" + now.getHours()).slice(-2) + ":" + ("0" + now.getMinutes()).slice(-2) + ":" + ("0" + now.getSeconds()).slice(-2) + ":" + ("00" + now.getMilliseconds()).slice(-3), 2613 method = loglevels[loglevel - 1], 2614 args = Array.prototype.splice.call(arguments, 1), 2615 func = Function.prototype.bind.call(console[method], console); 2616 args.unshift(time); 2617 func.apply(console, args); 2618 }; 2619 2620 /** 2621 * ------------------------------ 2622 * type testing 2623 * ------------------------------ 2624 */ 2625 2626 var _type = U.type = function (v) { 2627 return Object.prototype.toString.call(v).replace(/^\[object (.+)\]$/, "$1").toLowerCase(); 2628 }; 2629 _type.String = function (v) { 2630 return _type(v) === 'string'; 2631 }; 2632 _type.Function = function (v) { 2633 return _type(v) === 'function'; 2634 }; 2635 _type.Array = function (v) { 2636 return Array.isArray(v); 2637 }; 2638 _type.Number = function (v) { 2639 return !_type.Array(v) && (v - parseFloat(v) + 1) >= 0; 2640 }; 2641 _type.DomElement = function (o) { 2642 return ( 2643 typeof HTMLElement === "object" ? o instanceof HTMLElement : //DOM2 2644 o && typeof o === "object" && o !== null && o.nodeType === 1 && typeof o.nodeName === "string"); 2645 }; 2646 2647 /** 2648 * ------------------------------ 2649 * DOM Element info 2650 * ------------------------------ 2651 */ 2652 // always returns a list of matching DOM elements, from a selector, a DOM element or an list of elements or even an array of selectors 2653 var _get = U.get = {}; 2654 _get.elements = function (selector) { 2655 var arr = []; 2656 if (_type.String(selector)) { 2657 try { 2658 selector = document.querySelectorAll(selector); 2659 } catch (e) { // invalid selector 2660 return arr; 2661 } 2662 } 2663 if (_type(selector) === 'nodelist' || _type.Array(selector)) { 2664 for (var i = 0, ref = arr.length = selector.length; i < ref; i++) { // list of elements 2665 var elem = selector[i]; 2666 arr[i] = _type.DomElement(elem) ? elem : _get.elements(elem); // if not an element, try to resolve recursively 2667 } 2668 } else if (_type.DomElement(selector) || selector === document || selector === window) { 2669 arr = [selector]; // only the element 2670 } 2671 return arr; 2672 }; 2673 // get scroll top value 2674 _get.scrollTop = function (elem) { 2675 return (elem && typeof elem.scrollTop === 'number') ? elem.scrollTop : window.pageYOffset || 0; 2676 }; 2677 // get scroll left value 2678 _get.scrollLeft = function (elem) { 2679 return (elem && typeof elem.scrollLeft === 'number') ? elem.scrollLeft : window.pageXOffset || 0; 2680 }; 2681 // get element height 2682 _get.width = function (elem, outer, includeMargin) { 2683 return _dimension('width', elem, outer, includeMargin); 2684 }; 2685 // get element width 2686 _get.height = function (elem, outer, includeMargin) { 2687 return _dimension('height', elem, outer, includeMargin); 2688 }; 2689 2690 // get element position (optionally relative to viewport) 2691 _get.offset = function (elem, relativeToViewport) { 2692 var offset = { 2693 top: 0, 2694 left: 0 2695 }; 2696 if (elem && elem.getBoundingClientRect) { // check if available 2697 var rect = elem.getBoundingClientRect(); 2698 offset.top = rect.top; 2699 offset.left = rect.left; 2700 if (!relativeToViewport) { // clientRect is by default relative to viewport... 2701 offset.top += _get.scrollTop(); 2702 offset.left += _get.scrollLeft(); 2703 } 2704 } 2705 return offset; 2706 }; 2707 2708 /** 2709 * ------------------------------ 2710 * DOM Element manipulation 2711 * ------------------------------ 2712 */ 2713 2714 U.addClass = function (elem, classname) { 2715 if (classname) { 2716 if (elem.classList) elem.classList.add(classname); 2717 else elem.className += ' ' + classname; 2718 } 2719 }; 2720 U.removeClass = function (elem, classname) { 2721 if (classname) { 2722 if (elem.classList) elem.classList.remove(classname); 2723 else elem.className = elem.className.replace(new RegExp('(^|\\b)' + classname.split(' ').join('|') + '(\\b|$)', 'gi'), ' '); 2724 } 2725 }; 2726 // if options is string -> returns css value 2727 // if options is array -> returns object with css value pairs 2728 // if options is object -> set new css values 2729 U.css = function (elem, options) { 2730 if (_type.String(options)) { 2731 return _getComputedStyle(elem)[_camelCase(options)]; 2732 } else if (_type.Array(options)) { 2733 var 2734 obj = {}, 2735 style = _getComputedStyle(elem); 2736 options.forEach(function (option, key) { 2737 obj[option] = style[_camelCase(option)]; 2738 }); 2739 return obj; 2740 } else { 2741 for (var option in options) { 2742 var val = options[option]; 2743 if (val == parseFloat(val)) { // assume pixel for seemingly numerical values 2744 val += 'px'; 2745 } 2746 elem.style[_camelCase(option)] = val; 2747 } 2748 } 2749 }; 2750 2751 return U; 2752 }(window || {})); 2753 2754 ScrollMagic.Scene.prototype.addIndicators = function () { 2755 ScrollMagic._util.log(1, '(ScrollMagic.Scene) -> ERROR calling addIndicators() due to missing Plugin \'debug.addIndicators\'. Please make sure to include plugins/debug.addIndicators.js'); 2756 return this; 2757 } 2758 ScrollMagic.Scene.prototype.removeIndicators = function () { 2759 ScrollMagic._util.log(1, '(ScrollMagic.Scene) -> ERROR calling removeIndicators() due to missing Plugin \'debug.addIndicators\'. Please make sure to include plugins/debug.addIndicators.js'); 2760 return this; 2761 } 2762 ScrollMagic.Scene.prototype.setTween = function () { 2763 ScrollMagic._util.log(1, '(ScrollMagic.Scene) -> ERROR calling setTween() due to missing Plugin \'animation.gsap\'. Please make sure to include plugins/animation.gsap.js'); 2764 return this; 2765 } 2766 ScrollMagic.Scene.prototype.removeTween = function () { 2767 ScrollMagic._util.log(1, '(ScrollMagic.Scene) -> ERROR calling removeTween() due to missing Plugin \'animation.gsap\'. Please make sure to include plugins/animation.gsap.js'); 2768 return this; 2769 } 2770 ScrollMagic.Scene.prototype.setVelocity = function () { 2771 ScrollMagic._util.log(1, '(ScrollMagic.Scene) -> ERROR calling setVelocity() due to missing Plugin \'animation.velocity\'. Please make sure to include plugins/animation.velocity.js'); 2772 return this; 2773 } 2774 ScrollMagic.Scene.prototype.removeVelocity = function () { 2775 ScrollMagic._util.log(1, '(ScrollMagic.Scene) -> ERROR calling removeVelocity() due to missing Plugin \'animation.velocity\'. Please make sure to include plugins/animation.velocity.js'); 2776 return this; 2777 } 2778 2779 return ScrollMagic; 2780}));
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.