/*! * scrollmagic v2.0.3 (2015-04-07) * the javascript library for magical scroll interactions. * (c) 2015 jan paepke (@janpaepke) * project website: http://janpaepke.github.io/scrollmagic * * @version 2.0.3 * @license dual licensed under mit license and gpl. * @author jan paepke - e-mail@janpaepke.de * * @file scrollmagic main library. */ /** * @namespace scrollmagic */ (function (root, factory) { if (typeof define === 'function' && define.amd) { // amd. register as an anonymous module. define(factory); } else if (typeof exports === 'object') { // commonjs module.exports = factory(); } else { // browser global root.scrollmagic = factory(); } }(this, function () { "use strict"; var scrollmagic = function () { _util.log(2, '(compatibility notice) -> as of scrollmagic 2.0.0 you need to use \'new scrollmagic.controller()\' to create a new controller instance. use \'new scrollmagic.scene()\' to instance a scene.'); }; scrollmagic.version = "2.0.3"; // todo: temporary workaround for chrome's scroll jitter bug window.addeventlistener("mousewheel", function () {}); // global const var pin_spacer_attribute = "data-scrollmagic-pin-spacer"; /** * the main class that is needed once per scroll container. * * @class * * @example * // basic initialization * var controller = new scrollmagic.controller(); * * // passing options * var controller = new scrollmagic.controller({container: "#mycontainer", loglevel: 3}); * * @param {object} [options] - an object containing one or more options for the controller. * @param {(string|object)} [options.container=window] - a selector, dom object that references the main container for scrolling. * @param {boolean} [options.vertical=true] - sets the scroll mode to vertical (`true`) or horizontal (`false`) scrolling. * @param {object} [options.globalsceneoptions={}] - these options will be passed to every scene that is added to the controller using the addscene method. for more information on scene options see {@link scrollmagic.scene}. * @param {number} [options.loglevel=2] loglevel for debugging. note that logging is disabled in the minified version of scrollmagic. ** `0` => silent ** `1` => errors ** `2` => errors, warnings ** `3` => errors, warnings, debuginfo * @param {boolean} [options.refreshinterval=100] - some changes don't call events by default, like changing the container size or moving a scene trigger element. this interval polls these parameters to fire the necessary events. if you don't use custom containers, trigger elements or have static layouts, where the positions of the trigger elements don't change, you can set this to 0 disable interval checking and improve performance. * */ scrollmagic.controller = function (options) { /* * ---------------------------------------------------------------- * settings * ---------------------------------------------------------------- */ var namespace = "scrollmagic.controller", scroll_directions = { f: "forward", r: "reverse", p: "paused" }, default_options = controller_options.defaults; /* * ---------------------------------------------------------------- * private vars * ---------------------------------------------------------------- */ var controller = this, _options = _util.extend({}, default_options, options), _sceneobjects = [], _updatescenesonnextcycle = false, // can be boolean (true => all scenes) or an array of scenes to be updated _scrollpos = 0, _scrolldirection = scroll_directions.p, _isdocument = true, _viewportsize = 0, _enabled = true, _updatetimeout, _refreshtimeout; /* * ---------------------------------------------------------------- * private functions * ---------------------------------------------------------------- */ /** * internal constructor function of the scrollmagic controller * @private */ var construct = function () { for (var key in _options) { if (!default_options.hasownproperty(key)) { log(2, "warning: unknown option \"" + key + "\""); delete _options[key]; } } _options.container = _util.get.elements(_options.container)[0]; // check scrollcontainer if (!_options.container) { log(1, "error creating object " + namespace + ": no valid scroll container supplied"); throw namespace + " init failed."; // cancel } _isdocument = _options.container === window || _options.container === document.body || !document.body.contains(_options.container); // normalize to window if (_isdocument) { _options.container = window; } // update container size immediately _viewportsize = getviewportsize(); // set event handlers _options.container.addeventlistener("resize", onchange); _options.container.addeventlistener("scroll", onchange); _options.refreshinterval = parseint(_options.refreshinterval) || default_options.refreshinterval; schedulerefresh(); log(3, "added new " + namespace + " controller (v" + scrollmagic.version + ")"); }; /** * schedule the next execution of the refresh function * @private */ var schedulerefresh = function () { if (_options.refreshinterval > 0) { _refreshtimeout = window.settimeout(refresh, _options.refreshinterval); } }; /** * default function to get scroll pos - overwriteable using `controller.scrollpos(newfunction)` * @private */ var getscrollpos = function () { return _options.vertical ? _util.get.scrolltop(_options.container) : _util.get.scrollleft(_options.container); }; /** * returns the current viewport size (width vor horizontal, height for vertical) * @private */ var getviewportsize = function () { return _options.vertical ? _util.get.height(_options.container) : _util.get.width(_options.container); }; /** * default function to set scroll pos - overwriteable using `controller.scrollto(newfunction)` * make available publicly for pinned mousewheel workaround. * @private */ var setscrollpos = this._setscrollpos = function (pos) { if (_options.vertical) { if (_isdocument) { window.scrollto(_util.get.scrollleft(), pos); } else { _options.container.scrolltop = pos; } } else { if (_isdocument) { window.scrollto(pos, _util.get.scrolltop()); } else { _options.container.scrollleft = pos; } } }; /** * handle updates in cycles instead of on scroll (performance) * @private */ var updatescenes = function () { if (_enabled && _updatescenesonnextcycle) { // determine scenes to update var scenestoupdate = _util.type.array(_updatescenesonnextcycle) ? _updatescenesonnextcycle : _sceneobjects.slice(0); // reset scenes _updatescenesonnextcycle = false; var oldscrollpos = _scrollpos; // update scroll pos now instead of onchange, as it might have changed since scheduling (i.e. in-browser smooth scroll) _scrollpos = controller.scrollpos(); var deltascroll = _scrollpos - oldscrollpos; if (deltascroll !== 0) { // scroll position changed? _scrolldirection = (deltascroll > 0) ? scroll_directions.f : scroll_directions.r; } // reverse order of scenes if scrolling reverse if (_scrolldirection === scroll_directions.r) { scenestoupdate.reverse(); } // update scenes scenestoupdate.foreach(function (scene, index) { log(3, "updating scene " + (index + 1) + "/" + scenestoupdate.length + " (" + _sceneobjects.length + " total)"); scene.update(true); }); if (scenestoupdate.length === 0 && _options.loglevel >= 3) { log(3, "updating 0 scenes (nothing added to controller)"); } } }; /** * initializes raf callback * @private */ var debounceupdate = function () { _updatetimeout = _util.raf(updatescenes); }; /** * handles container changes * @private */ var onchange = function (e) { log(3, "event fired causing an update:", e.type); if (e.type == "resize") { // resize _viewportsize = getviewportsize(); _scrolldirection = scroll_directions.p; } // schedule update if (_updatescenesonnextcycle !== true) { _updatescenesonnextcycle = true; debounceupdate(); } }; var refresh = function () { if (!_isdocument) { // simulate resize event. only works for viewport relevant param (performance) if (_viewportsize != getviewportsize()) { var resizeevent; try { resizeevent = new event('resize', { bubbles: false, cancelable: false }); } catch (e) { // stupid ie resizeevent = document.createevent("event"); resizeevent.initevent("resize", false, false); } _options.container.dispatchevent(resizeevent); } } _sceneobjects.foreach(function (scene, index) { // refresh all scenes scene.refresh(); }); schedulerefresh(); }; /** * send a debug message to the console. * provided publicly with _log for plugins * @private * * @param {number} loglevel - the loglevel required to initiate output for the message. * @param {...mixed} output - one or more variables that should be passed to the console. */ var log = this._log = function (loglevel, output) { if (_options.loglevel >= loglevel) { array.prototype.splice.call(arguments, 1, 0, "(" + namespace + ") ->"); _util.log.apply(window, arguments); } }; // for scenes we have getters for each option, but for the controller we don't, so we need to make it available externally for plugins this._options = _options; /** * sort scenes in ascending order of their start offset. * @private * * @param {array} scenesarray - an array of scrollmagic scenes that should be sorted * @return {array} the sorted array of scenes. */ var sortscenes = function (scenesarray) { if (scenesarray.length <= 1) { return scenesarray; } else { var scenes = scenesarray.slice(0); scenes.sort(function (a, b) { return a.scrolloffset() > b.scrolloffset() ? 1 : -1; }); return scenes; } }; /** * ---------------------------------------------------------------- * public functions * ---------------------------------------------------------------- */ /** * add one ore more scene(s) to the controller. * this is the equivalent to `scene.addto(controller)`. * @public * @example * // with a previously defined scene * controller.addscene(scene); * * // with a newly created scene. * controller.addscene(new scrollmagic.scene({duration : 0})); * * // adding multiple scenes * controller.addscene([scene, scene2, new scrollmagic.scene({duration : 0})]); * * @param {(scrollmagic.scene|array)} newscene - scrollmagic scene or array of scenes to be added to the controller. * @return {controller} parent object for chaining. */ this.addscene = function (newscene) { if (_util.type.array(newscene)) { newscene.foreach(function (scene, index) { controller.addscene(scene); }); } else if (newscene instanceof scrollmagic.scene) { if (newscene.controller() !== controller) { newscene.addto(controller); } else if (_sceneobjects.indexof(newscene) < 0) { // new scene _sceneobjects.push(newscene); // add to array _sceneobjects = sortscenes(_sceneobjects); // sort newscene.on("shift.controller_sort", function () { // resort whenever scene moves _sceneobjects = sortscenes(_sceneobjects); }); // insert global defaults. for (var key in _options.globalsceneoptions) { if (newscene[key]) { newscene[key].call(newscene, _options.globalsceneoptions[key]); } } log(3, "adding scene (now " + _sceneobjects.length + " total)"); } } else { log(1, "error: invalid argument supplied for '.addscene()'"); } return controller; }; /** * remove one ore more scene(s) from the controller. * this is the equivalent to `scene.remove()`. * @public * @example * // remove a scene from the controller * controller.removescene(scene); * * // remove multiple scenes from the controller * controller.removescene([scene, scene2, scene3]); * * @param {(scrollmagic.scene|array)} scene - scrollmagic scene or array of scenes to be removed from the controller. * @returns {controller} parent object for chaining. */ this.removescene = function (scene) { if (_util.type.array(scene)) { scene.foreach(function (scene, index) { controller.removescene(scene); }); } else { var index = _sceneobjects.indexof(scene); if (index > -1) { scene.off("shift.controller_sort"); _sceneobjects.splice(index, 1); log(3, "removing scene (now " + _sceneobjects.length + " left)"); scene.remove(); } } return controller; }; /** * update one ore more scene(s) according to the scroll position of the container. * this is the equivalent to `scene.update()`. * the update method calculates the scene's start and end position (based on the trigger element, trigger hook, duration and offset) and checks it against the current scroll position of the container. * it then updates the current scene state accordingly (or does nothing, if the state is already correct) – pins will be set to their correct position and tweens will be updated to their correct progress. * _**note:** this method gets called constantly whenever controller detects a change. the only application for you is if you change something outside of the realm of scrollmagic, like moving the trigger or changing tween parameters._ * @public * @example * // update a specific scene on next cycle * controller.updatescene(scene); * * // update a specific scene immediately * controller.updatescene(scene, true); * * // update multiple scenes scene on next cycle * controller.updatescene([scene1, scene2, scene3]); * * @param {scrollmagic.scene} scene - scrollmagic scene or array of scenes that is/are supposed to be updated. * @param {boolean} [immediately=false] - if `true` the update will be instant, if `false` it will wait until next update cycle. this is useful when changing multiple properties of the scene - this way it will only be updated once all new properties are set (updatescenes). * @return {controller} parent object for chaining. */ this.updatescene = function (scene, immediately) { if (_util.type.array(scene)) { scene.foreach(function (scene, index) { controller.updatescene(scene, immediately); }); } else { if (immediately) { scene.update(true); } else if (_updatescenesonnextcycle !== true && scene instanceof scrollmagic.scene) { // if _updatescenesonnextcycle is true, all connected scenes are already scheduled for update // prep array for next update cycle _updatescenesonnextcycle = _updatescenesonnextcycle || []; if (_updatescenesonnextcycle.indexof(scene) == -1) { _updatescenesonnextcycle.push(scene); } _updatescenesonnextcycle = sortscenes(_updatescenesonnextcycle); // sort debounceupdate(); } } return controller; }; /** * updates the controller params and calls updatescene on every scene, that is attached to the controller. * see `controller.updatescene()` for more information about what this means. * in most cases you will not need this function, as it is called constantly, whenever scrollmagic detects a state change event, like resize or scroll. * the only application for this method is when scrollmagic fails to detect these events. * one application is with some external scroll libraries (like iscroll) that move an internal container to a negative offset instead of actually scrolling. in this case the update on the controller needs to be called whenever the child container's position changes. * for this case there will also be the need to provide a custom function to calculate the correct scroll position. see `controller.scrollpos()` for details. * @public * @example * // update the controller on next cycle (saves performance due to elimination of redundant updates) * controller.update(); * * // update the controller immediately * controller.update(true); * * @param {boolean} [immediately=false] - if `true` the update will be instant, if `false` it will wait until next update cycle (better performance) * @return {controller} parent object for chaining. */ this.update = function (immediately) { onchange({ type: "resize" }); // will update size and set _updatescenesonnextcycle to true if (immediately) { updatescenes(); } return controller; }; /** * scroll to a numeric scroll offset, a dom element, the start of a scene or provide an alternate method for scrolling. * for vertical controllers it will change the top scroll offset and for horizontal applications it will change the left offset. * @public * * @since 1.1.0 * @example * // scroll to an offset of 100 * controller.scrollto(100); * * // scroll to a dom element * controller.scrollto("#anchor"); * * // scroll to the beginning of a scene * var scene = new scrollmagic.scene({offset: 200}); * controller.scrollto(scene); * * // define a new scroll position modification function (jquery animate instead of jump) * controller.scrollto(function (newscrollpos) { * $("body").animate({scrolltop: newscrollpos}); * }); * controller.scrollto(100); // call as usual, but the new function will be used instead * * // define a new scroll function with an additional parameter * controller.scrollto(function (newscrollpos, message) { * console.log(message); * $(this).animate({scrolltop: newscrollpos}); * }); * // call as usual, but supply an extra parameter to the defined custom function * controller.scrollto(100, "my message"); * * // define a new scroll function with an additional parameter containing multiple variables * controller.scrollto(function (newscrollpos, options) { * someglobalvar = options.a + options.b; * $(this).animate({scrolltop: newscrollpos}); * }); * // call as usual, but supply an extra parameter containing multiple options * controller.scrollto(100, {a: 1, b: 2}); * * // define a new scroll function with a callback supplied as an additional parameter * controller.scrollto(function (newscrollpos, callback) { * $(this).animate({scrolltop: newscrollpos}, 400, "swing", callback); * }); * // call as usual, but supply an extra parameter, which is used as a callback in the previously defined custom scroll function * controller.scrollto(100, function() { * console.log("scroll has finished."); * }); * * @param {mixed} scrolltarget - the supplied argument can be one of these types: * 1. `number` -> the container will scroll to this new scroll offset. * 2. `string` or `object` -> can be a selector or a dom object. * the container will scroll to the position of this element. * 3. `scrollmagic scene` -> the container will scroll to the start of this scene. * 4. `function` -> this function will be used for future scroll position modifications. * this provides a way for you to change the behaviour of scrolling and adding new behaviour like animation. the function receives the new scroll position as a parameter and a reference to the container element using `this`. * it may also optionally receive an optional additional parameter (see below) * _**note:** * all other options will still work as expected, using the new function to scroll._ * @param {mixed} [additionalparameter] - if a custom scroll function was defined (see above 4.), you may want to supply additional parameters to it, when calling it. you can do this using this parameter – see examples for details. please note, that this parameter will have no effect, if you use the default scrolling function. * @returns {controller} parent object for chaining. */ this.scrollto = function (scrolltarget, additionalparameter) { if (_util.type.number(scrolltarget)) { // excecute setscrollpos.call(_options.container, scrolltarget, additionalparameter); } else if (scrolltarget instanceof scrollmagic.scene) { // scroll to scene if (scrolltarget.controller() === controller) { // check if the controller is associated with this scene controller.scrollto(scrolltarget.scrolloffset(), additionalparameter); } else { log(2, "scrollto(): the supplied scene does not belong to this controller. scroll cancelled.", scrolltarget); } } else if (_util.type.function(scrolltarget)) { // assign new scroll function setscrollpos = scrolltarget; } else { // scroll to element var elem = _util.get.elements(scrolltarget)[0]; if (elem) { // if parent is pin spacer, use spacer position instead so correct start position is returned for pinned elements. while (elem.parentnode.hasattribute(pin_spacer_attribute)) { elem = elem.parentnode; } var param = _options.vertical ? "top" : "left", // which param is of interest ? containeroffset = _util.get.offset(_options.container), // container position is needed because element offset is returned in relation to document, not in relation to container. elementoffset = _util.get.offset(elem); if (!_isdocument) { // container is not the document root, so substract scroll position to get correct trigger element position relative to scrollcontent containeroffset[param] -= controller.scrollpos(); } controller.scrollto(elementoffset[param] - containeroffset[param], additionalparameter); } else { log(2, "scrollto(): the supplied argument is invalid. scroll cancelled.", scrolltarget); } } return controller; }; /** * **get** the current scrollposition or **set** a new method to calculate it. * -> **get**: * when used as a getter this function will return the current scroll position. * to get a cached value use controller.info("scrollpos"), which will be updated in the update cycle. * for vertical controllers it will return the top scroll offset and for horizontal applications it will return the left offset. * * -> **set**: * when used as a setter this method prodes a way to permanently overwrite the controller's scroll position calculation. * a typical usecase is when the scroll position is not reflected by the containers scrolltop or scrollleft values, but for example by the inner offset of a child container. * moving a child container inside a parent is a commonly used method for several scrolling frameworks, including iscroll. * by providing an alternate calculation function you can make sure scrollmagic receives the correct scroll position. * please also bear in mind that your function should return y values for vertical scrolls an x for horizontals. * * to change the current scroll position please use `controller.scrollto()`. * @public * * @example * // get the current scroll position * var scrollpos = controller.scrollpos(); * * // set a new scroll position calculation method * controller.scrollpos(function () { * return this.info("vertical") ? -mychildcontainer.y : -mychildcontainer.x * }); * * @param {function} [scrollposmethod] - the function to be used for the scroll position calculation of the container. * @returns {(number|controller)} current scroll position or parent object for chaining. */ this.scrollpos = function (scrollposmethod) { if (!arguments.length) { // get return getscrollpos.call(controller); } else { // set if (_util.type.function(scrollposmethod)) { getscrollpos = scrollposmethod; } else { log(2, "provided value for method 'scrollpos' is not a function. to change the current scroll position use 'scrollto()'."); } } return controller; }; /** * **get** all infos or one in particular about the controller. * @public * @example * // returns the current scroll position (number) * var scrollpos = controller.info("scrollpos"); * * // returns all infos as an object * var infos = controller.info(); * * @param {string} [about] - if passed only this info will be returned instead of an object containing all. valid options are: ** `"size"` => the current viewport size of the container ** `"vertical"` => true if vertical scrolling, otherwise false ** `"scrollpos"` => the current scroll position ** `"scrolldirection"` => the last known direction of the scroll ** `"container"` => the container element ** `"isdocument"` => true if container element is the document. * @returns {(mixed|object)} the requested info(s). */ this.info = function (about) { var values = { size: _viewportsize, // contains height or width (in regard to orientation); vertical: _options.vertical, scrollpos: _scrollpos, scrolldirection: _scrolldirection, container: _options.container, isdocument: _isdocument }; if (!arguments.length) { // get all as an object return values; } else if (values[about] !== undefined) { return values[about]; } else { log(1, "error: option \"" + about + "\" is not available"); return; } }; /** * **get** or **set** the current loglevel option value. * @public * * @example * // get the current value * var loglevel = controller.loglevel(); * * // set a new value * controller.loglevel(3); * * @param {number} [newloglevel] - the new loglevel setting of the controller. `[0-3]` * @returns {(number|controller)} current loglevel or parent object for chaining. */ this.loglevel = function (newloglevel) { if (!arguments.length) { // get return _options.loglevel; } else if (_options.loglevel != newloglevel) { // set _options.loglevel = newloglevel; } return controller; }; /** * **get** or **set** the current enabled state of the controller. * this can be used to disable all scenes connected to the controller without destroying or removing them. * @public * * @example * // get the current value * var enabled = controller.enabled(); * * // disable the controller * controller.enabled(false); * * @param {boolean} [newstate] - the new enabled state of the controller `true` or `false`. * @returns {(boolean|controller)} current enabled state or parent object for chaining. */ this.enabled = function (newstate) { if (!arguments.length) { // get return _enabled; } else if (_enabled != newstate) { // set _enabled = !! newstate; controller.updatescene(_sceneobjects, true); } return controller; }; /** * destroy the controller, all scenes and everything. * @public * * @example * // without resetting the scenes * controller = controller.destroy(); * * // with scene reset * controller = controller.destroy(true); * * @param {boolean} [resetscenes=false] - if `true` the pins and tweens (if existent) of all scenes will be reset. * @returns {null} null to unset handler variables. */ this.destroy = function (resetscenes) { window.cleartimeout(_refreshtimeout); var i = _sceneobjects.length; while (i--) { _sceneobjects[i].destroy(resetscenes); } _options.container.removeeventlistener("resize", onchange); _options.container.removeeventlistener("scroll", onchange); _util.caf(_updatetimeout); log(3, "destroyed " + namespace + " (reset: " + (resetscenes ? "true" : "false") + ")"); return null; }; // init construct(); return controller; }; // store pagewide controller options var controller_options = { defaults: { container: window, vertical: true, globalsceneoptions: {}, loglevel: 2, refreshinterval: 100 } }; /* * method used to add an option to scrollmagic scenes. */ scrollmagic.controller.addoption = function (name, defaultvalue) { controller_options.defaults[name] = defaultvalue; }; // instance extension function for plugins scrollmagic.controller.extend = function (extension) { var oldclass = this; scrollmagic.controller = function () { oldclass.apply(this, arguments); this.$super = _util.extend({}, this); // copy parent state return extension.apply(this, arguments) || this; }; _util.extend(scrollmagic.controller, oldclass); // copy properties scrollmagic.controller.prototype = oldclass.prototype; // copy prototype scrollmagic.controller.prototype.constructor = scrollmagic.controller; // restore constructor }; /** * a scene defines where the controller should react and how. * * @class * * @example * // create a standard scene and add it to a controller * new scrollmagic.scene() * .addto(controller); * * // create a scene with custom options and assign a handler to it. * var scene = new scrollmagic.scene({ * duration: 100, * offset: 200, * triggerhook: "onenter", * reverse: false * }); * * @param {object} [options] - options for the scene. the options can be updated at any time. instead of setting the options for each scene individually you can also set them globally in the controller as the controllers `globalsceneoptions` option. the object accepts the same properties as the ones below. when a scene is added to the controller the options defined using the scene constructor will be overwritten by those set in `globalsceneoptions`. * @param {(number|function)} [options.duration=0] - the duration of the scene. if `0` tweens will auto-play when reaching the scene start point, pins will be pinned indefinetly starting at the start position. a function retuning the duration value is also supported. please see `scene.duration()` for details. * @param {number} [options.offset=0] - offset value for the trigger position. if no triggerelement is defined this will be the scroll distance from the start of the page, after which the scene will start. * @param {(string|object)} [options.triggerelement=null] - selector or dom object that defines the start of the scene. if undefined the scene will start right at the start of the page (unless an offset is set). * @param {(number|string)} [options.triggerhook="oncenter"] - can be a number between 0 and 1 defining the position of the trigger hook in relation to the viewport. can also be defined using a string: ** `"onenter"` => `1` ** `"oncenter"` => `0.5` ** `"onleave"` => `0` * @param {boolean} [options.reverse=true] - should the scene reverse, when scrolling up? * @param {number} [options.loglevel=2] - loglevel for debugging. note that logging is disabled in the minified version of scrollmagic. ** `0` => silent ** `1` => errors ** `2` => errors, warnings ** `3` => errors, warnings, debuginfo * */ scrollmagic.scene = function (options) { /* * ---------------------------------------------------------------- * settings * ---------------------------------------------------------------- */ var namespace = "scrollmagic.scene", default_options = scene_options.defaults; /* * ---------------------------------------------------------------- * private vars * ---------------------------------------------------------------- */ var scene = this, _options = _util.extend({}, default_options, options), _state = 'before', _progress = 0, _scrolloffset = { start: 0, end: 0 }, // reflects the controllers's scroll position for the start and end of the scene respectively _triggerpos = 0, _enabled = true, _durationupdatemethod, _controller; /** * internal constructor function of the scrollmagic scene * @private */ var construct = function () { for (var key in _options) { // check supplied options if (!default_options.hasownproperty(key)) { log(2, "warning: unknown option \"" + key + "\""); delete _options[key]; } } // add getters/setters for all possible options for (var optionname in default_options) { addsceneoption(optionname); } // validate all options validateoption(); // set event listeners scene.on("change.internal", function (e) { if (e.what !== "loglevel" && e.what !== "tweenchanges") { // no need for a scene update scene with these options... if (e.what === "triggerelement") { updatetriggerelementposition(); } else if (e.what === "reverse") { // the only property left that may have an impact on the current scene state. everything else is handled by the shift event. scene.update(); } } }).on("shift.internal", function (e) { updatescrolloffset(); scene.update(); // update scene to reflect new position }); }; /** * send a debug message to the console. * @private * but provided publicly with _log for plugins * * @param {number} loglevel - the loglevel required to initiate output for the message. * @param {...mixed} output - one or more variables that should be passed to the console. */ var log = this._log = function (loglevel, output) { if (_options.loglevel >= loglevel) { array.prototype.splice.call(arguments, 1, 0, "(" + namespace + ") ->"); _util.log.apply(window, arguments); } }; /** * add the scene to a controller. * this is the equivalent to `controller.addscene(scene)`. * @method scrollmagic.scene#addto * * @example * // add a scene to a scrollmagic controller * scene.addto(controller); * * @param {scrollmagic.controller} controller - the controller to which the scene should be added. * @returns {scene} parent object for chaining. */ this.addto = function (controller) { if (!(controller instanceof scrollmagic.controller)) { log(1, "error: supplied argument of 'addto()' is not a valid scrollmagic controller"); } else if (_controller != controller) { // new controller if (_controller) { // was associated to a different controller before, so remove it... _controller.removescene(scene); } _controller = controller; validateoption(); updateduration(true); updatetriggerelementposition(true); updatescrolloffset(); _controller.info("container").addeventlistener('resize', oncontainerresize); controller.addscene(scene); scene.trigger("add", { controller: _controller }); log(3, "added " + namespace + " to controller"); scene.update(); } return scene; }; /** * **get** or **set** the current enabled state of the scene. * this can be used to disable this scene without removing or destroying it. * @method scrollmagic.scene#enabled * * @example * // get the current value * var enabled = scene.enabled(); * * // disable the scene * scene.enabled(false); * * @param {boolean} [newstate] - the new enabled state of the scene `true` or `false`. * @returns {(boolean|scene)} current enabled state or parent object for chaining. */ this.enabled = function (newstate) { if (!arguments.length) { // get return _enabled; } else if (_enabled != newstate) { // set _enabled = !! newstate; scene.update(true); } return scene; }; /** * remove the scene from the controller. * this is the equivalent to `controller.removescene(scene)`. * the scene will not be updated anymore until you readd it to a controller. * to remove the pin or the tween you need to call removetween() or removepin() respectively. * @method scrollmagic.scene#remove * @example * // remove the scene from its controller * scene.remove(); * * @returns {scene} parent object for chaining. */ this.remove = function () { if (_controller) { _controller.info("container").removeeventlistener('resize', oncontainerresize); var tmpparent = _controller; _controller = undefined; tmpparent.removescene(scene); scene.trigger("remove"); log(3, "removed " + namespace + " from controller"); } return scene; }; /** * destroy the scene and everything. * @method scrollmagic.scene#destroy * @example * // destroy the scene without resetting the pin and tween to their initial positions * scene = scene.destroy(); * * // destroy the scene and reset the pin and tween * scene = scene.destroy(true); * * @param {boolean} [reset=false] - if `true` the pin and tween (if existent) will be reset. * @returns {null} null to unset handler variables. */ this.destroy = function (reset) { scene.trigger("destroy", { reset: reset }); scene.remove(); scene.off("*.*"); log(3, "destroyed " + namespace + " (reset: " + (reset ? "true" : "false") + ")"); return null; }; /** * updates the scene to reflect the current state. * this is the equivalent to `controller.updatescene(scene, immediately)`. * the update method calculates the scene's start and end position (based on the trigger element, trigger hook, duration and offset) and checks it against the current scroll position of the container. * it then updates the current scene state accordingly (or does nothing, if the state is already correct) – pins will be set to their correct position and tweens will be updated to their correct progress. * this means an update doesn't necessarily result in a progress change. the `progress` event will be fired if the progress has indeed changed between this update and the last. * _**note:** this method gets called constantly whenever scrollmagic detects a change. the only application for you is if you change something outside of the realm of scrollmagic, like moving the trigger or changing tween parameters._ * @method scrollmagic.scene#update * @example * // update the scene on next tick * scene.update(); * * // update the scene immediately * scene.update(true); * * @fires scene.update * * @param {boolean} [immediately=false] - if `true` the update will be instant, if `false` it will wait until next update cycle (better performance). * @returns {scene} parent object for chaining. */ this.update = function (immediately) { if (_controller) { if (immediately) { if (_controller.enabled() && _enabled) { var scrollpos = _controller.info("scrollpos"), newprogress; if (_options.duration > 0) { newprogress = (scrollpos - _scrolloffset.start) / (_scrolloffset.end - _scrolloffset.start); } else { newprogress = scrollpos >= _scrolloffset.start ? 1 : 0; } scene.trigger("update", { startpos: _scrolloffset.start, endpos: _scrolloffset.end, scrollpos: scrollpos }); scene.progress(newprogress); } else if (_pin && _state === "during") { updatepinstate(true); // unpin in position } } else { _controller.updatescene(scene, false); } } return scene; }; /** * updates dynamic scene variables like the trigger element position or the duration. * this method is automatically called in regular intervals from the controller. see {@link scrollmagic.controller} option `refreshinterval`. * * you can call it to minimize lag, for example when you intentionally change the position of the triggerelement. * if you don't it will simply be updated in the next refresh interval of the container, which is usually sufficient. * * @method scrollmagic.scene#refresh * @since 1.1.0 * @example * scene = new scrollmagic.scene({triggerelement: "#trigger"}); * * // change the position of the trigger * $("#trigger").css("top", 500); * // immediately let the scene know of this change * scene.refresh(); * * @fires {@link scene.shift}, if the trigger element position or the duration changed * @fires {@link scene.change}, if the duration changed * * @returns {scene} parent object for chaining. */ this.refresh = function () { updateduration(); updatetriggerelementposition(); // update trigger element position return scene; }; /** * **get** or **set** the scene's progress. * usually it shouldn't be necessary to use this as a setter, as it is set automatically by scene.update(). * the order in which the events are fired depends on the duration of the scene: * 1. scenes with `duration == 0`: * scenes that have no duration by definition have no ending. thus the `end` event will never be fired. * when the trigger position of the scene is passed the events are always fired in this order: * `enter`, `start`, `progress` when scrolling forward * and * `progress`, `start`, `leave` when scrolling in reverse * 2. scenes with `duration > 0`: * scenes with a set duration have a defined start and end point. * when scrolling past the start position of the scene it will fire these events in this order: * `enter`, `start`, `progress` * when continuing to scroll and passing the end point it will fire these events: * `progress`, `end`, `leave` * when reversing through the end point these events are fired: * `enter`, `end`, `progress` * and when continuing to scroll past the start position in reverse it will fire: * `progress`, `start`, `leave` * in between start and end the `progress` event will be called constantly, whenever the progress changes. * * in short: * `enter` events will always trigger **before** the progress update and `leave` envents will trigger **after** the progress update. * `start` and `end` will always trigger at their respective position. * * please review the event descriptions for details on the events and the event object that is passed to the callback. * * @method scrollmagic.scene#progress * @example * // get the current scene progress * var progress = scene.progress(); * * // set new scene progress * scene.progress(0.3); * * @fires {@link scene.enter}, when used as setter * @fires {@link scene.start}, when used as setter * @fires {@link scene.progress}, when used as setter * @fires {@link scene.end}, when used as setter * @fires {@link scene.leave}, when used as setter * * @param {number} [progress] - the new progress value of the scene `[0-1]`. * @returns {number} `get` - current scene progress. * @returns {scene} `set` - parent object for chaining. */ this.progress = function (progress) { if (!arguments.length) { // get return _progress; } else { // set var doupdate = false, oldstate = _state, scrolldirection = _controller ? _controller.info("scrolldirection") : 'paused', reverseorforward = _options.reverse || progress >= _progress; if (_options.duration === 0) { // zero duration scenes doupdate = _progress != progress; _progress = progress < 1 && reverseorforward ? 0 : 1; _state = _progress === 0 ? 'before' : 'during'; } else { // scenes with start and end if (progress <= 0 && _state !== 'before' && reverseorforward) { // go back to initial state _progress = 0; _state = 'before'; doupdate = true; } else if (progress > 0 && progress < 1 && reverseorforward) { _progress = progress; _state = 'during'; doupdate = true; } else if (progress >= 1 && _state !== 'after') { _progress = 1; _state = 'after'; doupdate = true; } else if (_state === 'during' && !reverseorforward) { updatepinstate(); // in case we scrolled backwards mid-scene and reverse is disabled => update the pin position, so it doesn't move back as well. } } if (doupdate) { // fire events var eventvars = { progress: _progress, state: _state, scrolldirection: scrolldirection }, statechanged = _state != oldstate; var trigger = function (eventname) { // tmp helper to simplify code scene.trigger(eventname, eventvars); }; if (statechanged) { // enter events if (oldstate !== 'during') { trigger("enter"); trigger(oldstate === 'before' ? "start" : "end"); } } trigger("progress"); if (statechanged) { // leave events if (_state !== 'during') { trigger(_state === 'before' ? "start" : "end"); trigger("leave"); } } } return scene; } }; /** * update the start and end scrolloffset of the container. * the positions reflect what the controller's scroll position will be at the start and end respectively. * is called, when: * - scene event "change" is called with: offset, triggerhook, duration * - scroll container event "resize" is called * - the position of the triggerelement changes * - the controller changes -> addto() * @private */ var updatescrolloffset = function () { _scrolloffset = { start: _triggerpos + _options.offset }; if (_controller && _options.triggerelement) { // take away triggerhook portion to get relative to top _scrolloffset.start -= _controller.info("size") * _options.triggerhook; } _scrolloffset.end = _scrolloffset.start + _options.duration; }; /** * updates the duration if set to a dynamic function. * this method is called when the scene is added to a controller and in regular intervals from the controller through scene.refresh(). * * @fires {@link scene.change}, if the duration changed * @fires {@link scene.shift}, if the duration changed * * @param {boolean} [suppressevents=false] - if true the shift event will be suppressed. * @private */ var updateduration = function (suppressevents) { // update duration if (_durationupdatemethod) { var varname = "duration"; if (changeoption(varname, _durationupdatemethod.call(scene)) && !suppressevents) { // set scene.trigger("change", { what: varname, newval: _options[varname] }); scene.trigger("shift", { reason: varname }); } } }; /** * updates the position of the triggerelement, if present. * this method is called ... * - ... when the triggerelement is changed * - ... when the scene is added to a (new) controller * - ... in regular intervals from the controller through scene.refresh(). * * @fires {@link scene.shift}, if the position changed * * @param {boolean} [suppressevents=false] - if true the shift event will be suppressed. * @private */ var updatetriggerelementposition = function (suppressevents) { var elementpos = 0, telem = _options.triggerelement; if (_controller && telem) { var controllerinfo = _controller.info(), containeroffset = _util.get.offset(controllerinfo.container), // container position is needed because element offset is returned in relation to document, not in relation to container. param = controllerinfo.vertical ? "top" : "left"; // which param is of interest ? // if parent is spacer, use spacer position instead so correct start position is returned for pinned elements. while (telem.parentnode.hasattribute(pin_spacer_attribute)) { telem = telem.parentnode; } var elementoffset = _util.get.offset(telem); if (!controllerinfo.isdocument) { // container is not the document root, so substract scroll position to get correct trigger element position relative to scrollcontent containeroffset[param] -= _controller.scrollpos(); } elementpos = elementoffset[param] - containeroffset[param]; } var changed = elementpos != _triggerpos; _triggerpos = elementpos; if (changed && !suppressevents) { scene.trigger("shift", { reason: "triggerelementposition" }); } }; /** * trigger a shift event, when the container is resized and the triggerhook is > 1. * @private */ var oncontainerresize = function (e) { if (_options.triggerhook > 0) { scene.trigger("shift", { reason: "containerresize" }); } }; var _validate = _util.extend(scene_options.validate, { // validation for duration handled internally for reference to private var _durationmethod duration: function (val) { if (_util.type.string(val) && val.match(/^(\.|\d)*\d+%$/)) { // percentage value var perc = parsefloat(val) / 100; val = function () { return _controller ? _controller.info("size") * perc : 0; }; } if (_util.type.function(val)) { // function _durationupdatemethod = val; try { val = parsefloat(_durationupdatemethod()); } catch (e) { val = -1; // will cause error below } } // val has to be float val = parsefloat(val); if (!_util.type.number(val) || val < 0) { if (_durationupdatemethod) { _durationupdatemethod = undefined; throw ["invalid return value of supplied function for option \"duration\":", val]; } else { throw ["invalid value for option \"duration\":", val]; } } return val; } }); /** * checks the validity of a specific or all options and reset to default if neccessary. * @private */ var validateoption = function (check) { check = arguments.length ? [check] : object.keys(_validate); check.foreach(function (optionname, key) { var value; if (_validate[optionname]) { // there is a validation method for this option try { // validate value value = _validate[optionname](_options[optionname]); } catch (e) { // validation failed -> reset to default value = default_options[optionname]; var logmsg = _util.type.string(e) ? [e] : e; if (_util.type.array(logmsg)) { logmsg[0] = "error: " + logmsg[0]; logmsg.unshift(1); // loglevel 1 for error msg log.apply(this, logmsg); } else { log(1, "error: problem executing validation callback for option '" + optionname + "':", e.message); } } finally { _options[optionname] = value; } } }); }; /** * helper used by the setter/getters for scene options * @private */ var changeoption = function (varname, newval) { var changed = false, oldval = _options[varname]; if (_options[varname] != newval) { _options[varname] = newval; validateoption(varname); // resets to default if necessary changed = oldval != _options[varname]; } return changed; }; // generate getters/setters for all options var addsceneoption = function (optionname) { if (!scene[optionname]) { scene[optionname] = function (newval) { if (!arguments.length) { // get return _options[optionname]; } else { if (optionname === "duration") { // new duration is set, so any previously set function must be unset _durationupdatemethod = undefined; } if (changeoption(optionname, newval)) { // set scene.trigger("change", { what: optionname, newval: _options[optionname] }); if (scene_options.shifts.indexof(optionname) > -1) { scene.trigger("shift", { reason: optionname }); } } } return scene; }; } }; /** * **get** or **set** the duration option value. * as a setter it also accepts a function returning a numeric value. * this is particularly useful for responsive setups. * * 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`). * _**note:** be aware that it's an easy way to kill performance, if you supply a function that has high cpu demand. * even for size and position calculations it is recommended to use a variable to cache the value. (see example) * this counts double if you use the same function for multiple scenes._ * * @method scrollmagic.scene#duration * @example * // get the current duration value * var duration = scene.duration(); * * // set a new duration * scene.duration(300); * * // use a function to automatically adjust the duration to the window height. * var durationvaluecache; * function getduration () { * return durationvaluecache; * } * function updateduration (e) { * durationvaluecache = window.innerheight; * } * $(window).on("resize", updateduration); // update the duration when the window size changes * $(window).triggerhandler("resize"); // set to initial value * scene.duration(getduration); // supply duration method * * @fires {@link scene.change}, when used as setter * @fires {@link scene.shift}, when used as setter * @param {(number|function)} [newduration] - the new duration of the scene. * @returns {number} `get` - current scene duration. * @returns {scene} `set` - parent object for chaining. */ /** * **get** or **set** the offset option value. * @method scrollmagic.scene#offset * @example * // get the current offset * var offset = scene.offset(); * * // set a new offset * scene.offset(100); * * @fires {@link scene.change}, when used as setter * @fires {@link scene.shift}, when used as setter * @param {number} [newoffset] - the new offset of the scene. * @returns {number} `get` - current scene offset. * @returns {scene} `set` - parent object for chaining. */ /** * **get** or **set** the triggerelement option value. * 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. * @method scrollmagic.scene#triggerelement * @example * // get the current triggerelement * var triggerelement = scene.triggerelement(); * * // set a new triggerelement using a selector * scene.triggerelement("#trigger"); * // set a new triggerelement using a dom object * scene.triggerelement(document.getelementbyid("trigger")); * * @fires {@link scene.change}, when used as setter * @param {(string|object)} [newtriggerelement] - the new trigger element for the scene. * @returns {(string|object)} `get` - current triggerelement. * @returns {scene} `set` - parent object for chaining. */ /** * **get** or **set** the triggerhook option value. * @method scrollmagic.scene#triggerhook * @example * // get the current triggerhook value * var triggerhook = scene.triggerhook(); * * // set a new triggerhook using a string * scene.triggerhook("onleave"); * // set a new triggerhook using a number * scene.triggerhook(0.7); * * @fires {@link scene.change}, when used as setter * @fires {@link scene.shift}, when used as setter * @param {(number|string)} [newtriggerhook] - the new triggerhook of the scene. see {@link scene} parameter description for value options. * @returns {number} `get` - current triggerhook (always numerical). * @returns {scene} `set` - parent object for chaining. */ /** * **get** or **set** the reverse option value. * @method scrollmagic.scene#reverse * @example * // get the current reverse option * var reverse = scene.reverse(); * * // set new reverse option * scene.reverse(false); * * @fires {@link scene.change}, when used as setter * @param {boolean} [newreverse] - the new reverse setting of the scene. * @returns {boolean} `get` - current reverse option value. * @returns {scene} `set` - parent object for chaining. */ /** * **get** or **set** the loglevel option value. * @method scrollmagic.scene#loglevel * @example * // get the current loglevel * var loglevel = scene.loglevel(); * * // set new loglevel * scene.loglevel(3); * * @fires {@link scene.change}, when used as setter * @param {number} [newloglevel] - the new loglevel setting of the scene. `[0-3]` * @returns {number} `get` - current loglevel. * @returns {scene} `set` - parent object for chaining. */ /** * **get** the associated controller. * @method scrollmagic.scene#controller * @example * // get the controller of a scene * var controller = scene.controller(); * * @returns {scrollmagic.controller} parent controller or `undefined` */ this.controller = function () { return _controller; }; /** * **get** the current state. * @method scrollmagic.scene#state * @example * // get the current state * var state = scene.state(); * * @returns {string} `"before"`, `"during"` or `"after"` */ this.state = function () { return _state; }; /** * **get** the current scroll offset for the start of the scene. * mind, that the scrolloffset is related to the size of the container, if `triggerhook` is bigger than `0` (or `"onleave"`). * this means, that resizing the container or changing the `triggerhook` will influence the scene's start offset. * @method scrollmagic.scene#scrolloffset * @example * // get the current scroll offset for the start and end of the scene. * var start = scene.scrolloffset(); * var end = scene.scrolloffset() + scene.duration(); * console.log("the scene starts at", start, "and ends at", end); * * @returns {number} the scroll offset (of the container) at which the scene will trigger. y value for vertical and x value for horizontal scrolls. */ this.scrolloffset = function () { return _scrolloffset.start; }; /** * **get** the trigger position of the scene (including the value of the `offset` option). * @method scrollmagic.scene#triggerposition * @example * // get the scene's trigger position * var triggerposition = scene.triggerposition(); * * @returns {number} start position of the scene. top position value for vertical and left position value for horizontal scrolls. */ this.triggerposition = function () { var pos = _options.offset; // the offset is the basis if (_controller) { // get the trigger position if (_options.triggerelement) { // element as trigger pos += _triggerpos; } else { // return the height of the triggerhook to start at the beginning pos += _controller.info("size") * scene.triggerhook(); } } return pos; }; /* * ---------------------------------------------------------------- * event management * ---------------------------------------------------------------- */ var _listeners = {}; /** * scene start event. * fires whenever the scroll position its the starting point of the scene. * 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. * * for details on this event and the order in which it is fired, please review the {@link scene.progress} method. * * @event scrollmagic.scene#start * * @example * scene.on("start", function (event) { * console.log("hit start point of scene."); * }); * * @property {object} event - the event object passed to each callback * @property {string} event.type - the name of the event * @property {scene} event.target - the scene object that triggered this event * @property {number} event.progress - reflects the current progress of the scene * @property {string} event.state - the current state of the scene `"before"` or `"during"` * @property {string} event.scrolldirection - indicates which way we are scrolling `"paused"`, `"forward"` or `"reverse"` */ /** * scene end event. * fires whenever the scroll position its the ending point of the scene. * 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. * * for details on this event and the order in which it is fired, please review the {@link scene.progress} method. * * @event scrollmagic.scene#end * * @example * scene.on("end", function (event) { * console.log("hit end point of scene."); * }); * * @property {object} event - the event object passed to each callback * @property {string} event.type - the name of the event * @property {scene} event.target - the scene object that triggered this event * @property {number} event.progress - reflects the current progress of the scene * @property {string} event.state - the current state of the scene `"during"` or `"after"` * @property {string} event.scrolldirection - indicates which way we are scrolling `"paused"`, `"forward"` or `"reverse"` */ /** * scene enter event. * fires whenever the scene enters the "during" state. * keep in mind that it doesn't matter if the scene plays forward or backward: this event always fires when the scene enters its active scroll timeframe, regardless of the scroll-direction. * * for details on this event and the order in which it is fired, please review the {@link scene.progress} method. * * @event scrollmagic.scene#enter * * @example * scene.on("enter", function (event) { * console.log("scene entered."); * }); * * @property {object} event - the event object passed to each callback * @property {string} event.type - the name of the event * @property {scene} event.target - the scene object that triggered this event * @property {number} event.progress - reflects the current progress of the scene * @property {string} event.state - the current state of the scene - always `"during"` * @property {string} event.scrolldirection - indicates which way we are scrolling `"paused"`, `"forward"` or `"reverse"` */ /** * scene leave event. * fires whenever the scene's state goes from "during" to either "before" or "after". * 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. * * for details on this event and the order in which it is fired, please review the {@link scene.progress} method. * * @event scrollmagic.scene#leave * * @example * scene.on("leave", function (event) { * console.log("scene left."); * }); * * @property {object} event - the event object passed to each callback * @property {string} event.type - the name of the event * @property {scene} event.target - the scene object that triggered this event * @property {number} event.progress - reflects the current progress of the scene * @property {string} event.state - the current state of the scene `"before"` or `"after"` * @property {string} event.scrolldirection - indicates which way we are scrolling `"paused"`, `"forward"` or `"reverse"` */ /** * scene update event. * fires whenever the scene is updated (but not necessarily changes the progress). * * @event scrollmagic.scene#update * * @example * scene.on("update", function (event) { * console.log("scene updated."); * }); * * @property {object} event - the event object passed to each callback * @property {string} event.type - the name of the event * @property {scene} event.target - the scene object that triggered this event * @property {number} event.startpos - the starting position of the scene (in relation to the conainer) * @property {number} event.endpos - the ending position of the scene (in relation to the conainer) * @property {number} event.scrollpos - the current scroll position of the container */ /** * scene progress event. * fires whenever the progress of the scene changes. * * for details on this event and the order in which it is fired, please review the {@link scene.progress} method. * * @event scrollmagic.scene#progress * * @example * scene.on("progress", function (event) { * console.log("scene progress changed to " + event.progress); * }); * * @property {object} event - the event object passed to each callback * @property {string} event.type - the name of the event * @property {scene} event.target - the scene object that triggered this event * @property {number} event.progress - reflects the current progress of the scene * @property {string} event.state - the current state of the scene `"before"`, `"during"` or `"after"` * @property {string} event.scrolldirection - indicates which way we are scrolling `"paused"`, `"forward"` or `"reverse"` */ /** * scene change event. * fires whenvever a property of the scene is changed. * * @event scrollmagic.scene#change * * @example * scene.on("change", function (event) { * console.log("scene property \"" + event.what + "\" changed to " + event.newval); * }); * * @property {object} event - the event object passed to each callback * @property {string} event.type - the name of the event * @property {scene} event.target - the scene object that triggered this event * @property {string} event.what - indicates what value has been changed * @property {mixed} event.newval - the new value of the changed property */ /** * scene shift event. * fires whenvever the start or end **scroll offset** of the scene change. * this happens explicitely, when one of these values change: `offset`, `duration` or `triggerhook`. * it will fire implicitly when the `triggerelement` changes, if the new element has a different position (most cases). * it will also fire implicitly when the size of the container changes and the triggerhook is anything other than `onleave`. * * @event scrollmagic.scene#shift * @since 1.1.0 * * @example * scene.on("shift", function (event) { * console.log("scene moved, because the " + event.reason + " has changed.)"); * }); * * @property {object} event - the event object passed to each callback * @property {string} event.type - the name of the event * @property {scene} event.target - the scene object that triggered this event * @property {string} event.reason - indicates why the scene has shifted */ /** * scene destroy event. * fires whenvever the scene is destroyed. * this can be used to tidy up custom behaviour used in events. * * @event scrollmagic.scene#destroy * @since 1.1.0 * * @example * scene.on("enter", function (event) { * // add custom action * $("#my-elem").left("200"); * }) * .on("destroy", function (event) { * // reset my element to start position * if (event.reset) { * $("#my-elem").left("0"); * } * }); * * @property {object} event - the event object passed to each callback * @property {string} event.type - the name of the event * @property {scene} event.target - the scene object that triggered this event * @property {boolean} event.reset - indicates if the destroy method was called with reset `true` or `false`. */ /** * scene add event. * fires when the scene is added to a controller. * this is mostly used by plugins to know that change might be due. * * @event scrollmagic.scene#add * @since 2.0.0 * * @example * scene.on("add", function (event) { * console.log('scene was added to a new controller.'); * }); * * @property {object} event - the event object passed to each callback * @property {string} event.type - the name of the event * @property {scene} event.target - the scene object that triggered this event * @property {boolean} event.controller - the controller object the scene was added to. */ /** * scene remove event. * fires when the scene is removed from a controller. * this is mostly used by plugins to know that change might be due. * * @event scrollmagic.scene#remove * @since 2.0.0 * * @example * scene.on("remove", function (event) { * console.log('scene was removed from its controller.'); * }); * * @property {object} event - the event object passed to each callback * @property {string} event.type - the name of the event * @property {scene} event.target - the scene object that triggered this event */ /** * add one ore more event listener. * the callback function will be fired at the respective event, and an object containing relevant data will be passed to the callback. * @method scrollmagic.scene#on * * @example * function callback (event) { * console.log("event fired! (" + event.type + ")"); * } * // add listeners * scene.on("change update progress start end enter leave", callback); * * @param {string} names - the name or names of the event the callback should be attached to. * @param {function} callback - a function that should be executed, when the event is dispatched. an event object will be passed to the callback. * @returns {scene} parent object for chaining. */ this.on = function (names, callback) { if (_util.type.function(callback)) { names = names.trim().split(' '); names.foreach(function (fullname) { var nameparts = fullname.split('.'), eventname = nameparts[0], namespace = nameparts[1]; if (eventname != "*") { // disallow wildcards if (!_listeners[eventname]) { _listeners[eventname] = []; } _listeners[eventname].push({ namespace: namespace || '', callback: callback }); } }); } else { log(1, "error when calling '.on()': supplied callback for '" + names + "' is not a valid function!"); } return scene; }; /** * remove one or more event listener. * @method scrollmagic.scene#off * * @example * function callback (event) { * console.log("event fired! (" + event.type + ")"); * } * // add listeners * scene.on("change update", callback); * // remove listeners * scene.off("change update", callback); * * @param {string} names - the name or names of the event that should be removed. * @param {function} [callback] - a specific callback function that should be removed. if none is passed all callbacks to the event listener will be removed. * @returns {scene} parent object for chaining. */ this.off = function (names, callback) { if (!names) { log(1, "error: invalid event name supplied."); return scene; } names = names.trim().split(' '); names.foreach(function (fullname, key) { var nameparts = fullname.split('.'), eventname = nameparts[0], namespace = nameparts[1] || '', removelist = eventname === '*' ? object.keys(_listeners) : [eventname]; removelist.foreach(function (remove) { var list = _listeners[remove] || [], i = list.length; while (i--) { var listener = list[i]; if (listener && (namespace === listener.namespace || namespace === '*') && (!callback || callback == listener.callback)) { list.splice(i, 1); } } if (!list.length) { delete _listeners[remove]; } }); }); return scene; }; /** * trigger an event. * @method scrollmagic.scene#trigger * * @example * this.trigger("change"); * * @param {string} name - the name of the event that should be triggered. * @param {object} [vars] - an object containing info that should be passed to the callback. * @returns {scene} parent object for chaining. */ this.trigger = function (name, vars) { if (name) { var nameparts = name.trim().split('.'), eventname = nameparts[0], namespace = nameparts[1], listeners = _listeners[eventname]; log(3, 'event fired:', eventname, vars ? "->" : '', vars || ''); if (listeners) { listeners.foreach(function (listener, key) { if (!namespace || namespace === listener.namespace) { listener.callback.call(scene, new scrollmagic.event(eventname, listener.namespace, scene, vars)); } }); } } else { log(1, "error: invalid event name supplied."); } return scene; }; var _pin, _pinoptions; scene.on("shift.internal", function (e) { var durationchanged = e.reason === "duration"; if ((_state === "after" && durationchanged) || (_state === 'during' && _options.duration === 0)) { // 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]. updatepinstate(); } if (durationchanged) { updatepindimensions(); } }).on("progress.internal", function (e) { updatepinstate(); }).on("add.internal", function (e) { updatepindimensions(); }).on("destroy.internal", function (e) { scene.removepin(e.reset); }); /** * update the pin state. * @private */ var updatepinstate = function (forceunpin) { if (_pin && _controller) { var containerinfo = _controller.info(); if (!forceunpin && _state === "during") { // during scene or if duration is 0 and we are past the trigger // pinned state if (_util.css(_pin, "position") != "fixed") { // change state before updating pin spacer (position changes due to fixed collapsing might occur.) _util.css(_pin, { "position": "fixed" }); // update pin spacer updatepindimensions(); } var fixedpos = _util.get.offset(_pinoptions.spacer, true), // get viewport position of spacer scrolldistance = _options.reverse || _options.duration === 0 ? containerinfo.scrollpos - _scrolloffset.start // quicker : math.round(_progress * _options.duration * 10) / 10; // if no reverse and during pin the position needs to be recalculated using the progress // add scrolldistance fixedpos[containerinfo.vertical ? "top" : "left"] += scrolldistance; // set new values _util.css(_pin, { top: fixedpos.top, left: fixedpos.left }); } else { // unpinned state var newcss = { position: _pinoptions.inflow ? "relative" : "absolute", top: 0, left: 0 }, change = _util.css(_pin, "position") != newcss.position; if (!_pinoptions.pushfollowers) { newcss[containerinfo.vertical ? "top" : "left"] = _options.duration * _progress; } else if (_options.duration > 0) { // only concerns scenes with duration if (_state === "after" && parsefloat(_util.css(_pinoptions.spacer, "padding-top")) === 0) { change = true; // if in after state but havent updated spacer yet (jumped past pin) } else if (_state === "before" && parsefloat(_util.css(_pinoptions.spacer, "padding-bottom")) === 0) { // before change = true; // jumped past fixed state upward direction } } // set new values _util.css(_pin, newcss); if (change) { // update pin spacer if state changed updatepindimensions(); } } } }; /** * update the pin spacer and/or element size. * the size of the spacer needs to be updated whenever the duration of the scene changes, if it is to push down following elements. * @private */ var updatepindimensions = function () { if (_pin && _controller && _pinoptions.inflow) { // no spacerresize, if original position is absolute var after = (_state === "after"), before = (_state === "before"), during = (_state === "during"), vertical = _controller.info("vertical"), spacerchild = _pinoptions.spacer.children[0], // usually the pined element but can also be another spacer (cascaded pins) margincollapse = _util.ismargincollapsetype(_util.css(_pinoptions.spacer, "display")), css = {}; // set new size // if relsize: spacer -> pin | else: pin -> spacer if (_pinoptions.relsize.width || _pinoptions.relsize.autofullwidth) { if (during) { _util.css(_pin, { "width": _util.get.width(_pinoptions.spacer) }); } else { _util.css(_pin, { "width": "100%" }); } } else { // minwidth is needed for cascaded pins. css["min-width"] = _util.get.width(vertical ? _pin : spacerchild, true, true); css.width = during ? css["min-width"] : "auto"; } if (_pinoptions.relsize.height) { if (during) { // the only padding the spacer should ever include is the duration (if pushfollowers = true), so we need to substract that. _util.css(_pin, { "height": _util.get.height(_pinoptions.spacer) - (_pinoptions.pushfollowers ? _options.duration : 0) }); } else { _util.css(_pin, { "height": "100%" }); } } else { // margin is only included if it's a cascaded pin to resolve an ie9 bug css["min-height"] = _util.get.height(vertical ? spacerchild : _pin, true, !margincollapse); // needed for cascading pins css.height = during ? css["min-height"] : "auto"; } // add space for duration if pushfollowers is true if (_pinoptions.pushfollowers) { css["padding" + (vertical ? "top" : "left")] = _options.duration * _progress; css["padding" + (vertical ? "bottom" : "right")] = _options.duration * (1 - _progress); } _util.css(_pinoptions.spacer, css); } }; /** * updates the pin state (in certain scenarios) * 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. * so this function is called on resize and scroll of the document. * @private */ var updatepinincontainer = function () { if (_controller && _pin && _state === "during" && !_controller.info("isdocument")) { updatepinstate(); } }; /** * updates the pin spacer size state (in certain scenarios) * if container is resized during pin and relatively sized the size of the pin might need to be updated... * so this function is called on resize of the container. * @private */ var updaterelativepinspacer = function () { if (_controller && _pin && // well, duh _state === "during" && // element in pinned state? ( // is width or height relatively sized, but not in relation to body? then we need to recalc. ((_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)))) { updatepindimensions(); } }; /** * is called, when the mousewhel is used while over a pinned element inside a div container. * if the scene is in fixed state scroll events would be counted towards the body. this forwards the event to the scroll container. * @private */ var onmousewheeloverpin = function (e) { if (_controller && _pin && _state === "during" && !_controller.info("isdocument")) { // in pin state e.preventdefault(); _controller._setscrollpos(_controller.info("scrollpos") - ((e.wheeldelta || e[_controller.info("vertical") ? "wheeldeltay" : "wheeldeltax"]) / 3 || -e.detail * 30)); } }; /** * pin an element for the duration of the tween. * if the scene duration is 0 the element will only be unpinned, if the user scrolls back past the start position. * make sure only one pin is applied to an element at the same time. * an element can be pinned multiple times, but only successively. * _**note:** the option `pushfollowers` has no effect, when the scene duration is 0._ * @method scrollmagic.scene#setpin * @example * // pin element and push all following elements down by the amount of the pin duration. * scene.setpin("#pin"); * * // pin element and keeping all following elements in their place. the pinned element will move past them. * scene.setpin("#pin", {pushfollowers: false}); * * @param {(string|object)} element - a selector targeting an element or a dom object that is supposed to be pinned. * @param {object} [settings] - settings for the pin * @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. ignored, when duration is `0`. * @param {string} [settings.spacerclass="scrollmagic-pin-spacer"] - classname of the pin spacer element, which is used to replace the element. * * @returns {scene} parent object for chaining. */ this.setpin = function (element, settings) { var defaultsettings = { pushfollowers: true, spacerclass: "scrollmagic-pin-spacer" }; settings = _util.extend({}, defaultsettings, settings); // validate element element = _util.get.elements(element)[0]; if (!element) { log(1, "error calling method 'setpin()': invalid pin element supplied."); return scene; // cancel } else if (_util.css(element, "position") === "fixed") { log(1, "error calling method 'setpin()': pin does not work with elements that are positioned 'fixed'."); return scene; // cancel } if (_pin) { // preexisting pin? if (_pin === element) { // same pin we already have -> do nothing return scene; // cancel } else { // kill old pin scene.removepin(); } } _pin = element; var parentdisplay = _pin.parentnode.style.display, boundsparams = ["top", "left", "bottom", "right", "margin", "marginleft", "marginright", "margintop", "marginbottom"]; _pin.parentnode.style.display = 'none'; // hack start to force css to return stylesheet values instead of calculated px values. var inflow = _util.css(_pin, "position") != "absolute", pincss = _util.css(_pin, boundsparams.concat(["display"])), sizecss = _util.css(_pin, ["width", "height"]); _pin.parentnode.style.display = parentdisplay; // hack end. if (!inflow && settings.pushfollowers) { log(2, "warning: if the pinned element is positioned absolutely pushfollowers will be disabled."); settings.pushfollowers = false; } window.settimeout(function () { // wait until all finished, because with responsive duration it will only be set after scene is added to controller if (_pin && _options.duration === 0 && settings.pushfollowers) { log(2, "warning: pushfollowers =", true, "has no effect, when scene duration is 0."); } }, 0); // create spacer and insert var spacer = _pin.parentnode.insertbefore(document.createelement('div'), _pin), spacercss = _util.extend(pincss, { position: inflow ? "relative" : "absolute", boxsizing: "content-box", mozboxsizing: "content-box", webkitboxsizing: "content-box" }); if (!inflow) { // copy size if positioned absolutely, to work for bottom/right positioned elements. _util.extend(spacercss, _util.css(_pin, ["width", "height"])); } _util.css(spacer, spacercss); spacer.setattribute(pin_spacer_attribute, ""); _util.addclass(spacer, settings.spacerclass); // set the pin options _pinoptions = { spacer: spacer, relsize: { // save if size is defined using % values. if so, handle spacer resize differently... width: sizecss.width.slice(-1) === "%", height: sizecss.height.slice(-1) === "%", autofullwidth: sizecss.width === "auto" && inflow && _util.ismargincollapsetype(pincss.display) }, pushfollowers: settings.pushfollowers, inflow: inflow, // stores if the element takes up space in the document flow }; if (!_pin.___origstyle) { _pin.___origstyle = {}; var pininlinecss = _pin.style, copystyles = boundsparams.concat(["width", "height", "position", "boxsizing", "mozboxsizing", "webkitboxsizing"]); copystyles.foreach(function (val) { _pin.___origstyle[val] = pininlinecss[val] || ""; }); } // if relative size, transfer it to spacer and make pin calculate it... if (_pinoptions.relsize.width) { _util.css(spacer, { width: sizecss.width }); } if (_pinoptions.relsize.height) { _util.css(spacer, { height: sizecss.height }); } // now place the pin element inside the spacer spacer.appendchild(_pin); // and set new css _util.css(_pin, { position: inflow ? "relative" : "absolute", margin: "auto", top: "auto", left: "auto", bottom: "auto", right: "auto" }); if (_pinoptions.relsize.width || _pinoptions.relsize.autofullwidth) { _util.css(_pin, { boxsizing: "border-box", mozboxsizing: "border-box", webkitboxsizing: "border-box" }); } // add listener to document to update pin position in case controller is not the document. window.addeventlistener('scroll', updatepinincontainer); window.addeventlistener('resize', updatepinincontainer); window.addeventlistener('resize', updaterelativepinspacer); // add mousewheel listener to catch scrolls over fixed elements _pin.addeventlistener("mousewheel", onmousewheeloverpin); _pin.addeventlistener("dommousescroll", onmousewheeloverpin); log(3, "added pin"); // finally update the pin to init updatepinstate(); return scene; }; /** * remove the pin from the scene. * @method scrollmagic.scene#removepin * @example * // remove the pin from the scene without resetting it (the spacer is not removed) * scene.removepin(); * * // remove the pin from the scene and reset the pin element to its initial position (spacer is removed) * scene.removepin(true); * * @param {boolean} [reset=false] - if `false` the spacer will not be removed and the element's position will not be reset. * @returns {scene} parent object for chaining. */ this.removepin = function (reset) { if (_pin) { if (_state === "during") { updatepinstate(true); // force unpin at position } if (reset || !_controller) { // if there's no controller no progress was made anyway... var spacerchild = _pinoptions.spacer.children[0]; // usually the pin element, but may be another spacer... if (spacerchild.hasattribute(pin_spacer_attribute)) { // copy margins to child spacer var style = _pinoptions.spacer.style, values = ["margin", "marginleft", "marginright", "margintop", "marginbottom"]; margins = {}; values.foreach(function (val) { margins[val] = style[val] || ""; }); _util.css(spacerchild, margins); } _pinoptions.spacer.parentnode.insertbefore(spacerchild, _pinoptions.spacer); _pinoptions.spacer.parentnode.removechild(_pinoptions.spacer); if (!_pin.parentnode.hasattribute(pin_spacer_attribute)) { // if it's the last pin for this element -> restore inline styles // todo: only correctly set for first pin (when cascading) - how to fix? _util.css(_pin, _pin.___origstyle); delete _pin.___origstyle; } } window.removeeventlistener('scroll', updatepinincontainer); window.removeeventlistener('resize', updatepinincontainer); window.removeeventlistener('resize', updaterelativepinspacer); _pin.removeeventlistener("mousewheel", onmousewheeloverpin); _pin.removeeventlistener("dommousescroll", onmousewheeloverpin); _pin = undefined; log(3, "removed pin (reset: " + (reset ? "true" : "false") + ")"); } return scene; }; var _cssclasses, _cssclasselems = []; scene.on("destroy.internal", function (e) { scene.removeclasstoggle(e.reset); }); /** * define a css class modification while the scene is active. * when the scene triggers the classes will be added to the supplied element and removed, when the scene is over. * if the scene duration is 0 the classes will only be removed if the user scrolls back past the start position. * @method scrollmagic.scene#setclasstoggle * @example * // add the class 'myclass' to the element with the id 'my-elem' for the duration of the scene * scene.setclasstoggle("#my-elem", "myclass"); * * // add multiple classes to multiple elements defined by the selector '.classchange' * scene.setclasstoggle(".classchange", "class1 class2 class3"); * * @param {(string|object)} element - a selector targeting one or more elements or a dom object that is supposed to be modified. * @param {string} classes - one or more classnames (separated by space) that should be added to the element during the scene. * * @returns {scene} parent object for chaining. */ this.setclasstoggle = function (element, classes) { var elems = _util.get.elements(element); if (elems.length === 0 || !_util.type.string(classes)) { log(1, "error calling method 'setclasstoggle()': invalid " + (elems.length === 0 ? "element" : "classes") + " supplied."); return scene; } if (_cssclasselems.length > 0) { // remove old ones scene.removeclasstoggle(); } _cssclasses = classes; _cssclasselems = elems; scene.on("enter.internal_class leave.internal_class", function (e) { var toggle = e.type === "enter" ? _util.addclass : _util.removeclass; _cssclasselems.foreach(function (elem, key) { toggle(elem, _cssclasses); }); }); return scene; }; /** * remove the class binding from the scene. * @method scrollmagic.scene#removeclasstoggle * @example * // remove class binding from the scene without reset * scene.removeclasstoggle(); * * // remove class binding and remove the changes it caused * scene.removeclasstoggle(true); * * @param {boolean} [reset=false] - if `false` and the classes are currently active, they will remain on the element. if `true` they will be removed. * @returns {scene} parent object for chaining. */ this.removeclasstoggle = function (reset) { if (reset) { _cssclasselems.foreach(function (elem, key) { _util.removeclass(elem, _cssclasses); }); } scene.off("start.internal_class end.internal_class"); _cssclasses = undefined; _cssclasselems = []; return scene; }; // init construct(); return scene; }; // store pagewide scene options var scene_options = { defaults: { duration: 0, offset: 0, triggerelement: undefined, triggerhook: 0.5, reverse: true, loglevel: 2 }, validate: { offset: function (val) { val = parsefloat(val); if (!_util.type.number(val)) { throw ["invalid value for option \"offset\":", val]; } return val; }, triggerelement: function (val) { val = val || undefined; if (val) { var elem = _util.get.elements(val)[0]; if (elem) { val = elem; } else { throw ["element defined in option \"triggerelement\" was not found:", val]; } } return val; }, triggerhook: function (val) { var translate = { "oncenter": 0.5, "onenter": 1, "onleave": 0 }; if (_util.type.number(val)) { val = math.max(0, math.min(parsefloat(val), 1)); // make sure its betweeen 0 and 1 } else if (val in translate) { val = translate[val]; } else { throw ["invalid value for option \"triggerhook\": ", val]; } return val; }, reverse: function (val) { return !!val; // force boolean }, loglevel: function (val) { val = parseint(val); if (!_util.type.number(val) || val < 0 || val > 3) { throw ["invalid value for option \"loglevel\":", val]; } return val; } }, // holder for validation methods. duration validation is handled in 'getters-setters.js' shifts: ["duration", "offset", "triggerhook"], // list of options that trigger a `shift` event }; /* * method used to add an option to scrollmagic scenes. * todo: doc (private for dev) */ scrollmagic.scene.addoption = function (name, defaultvalue, validationcallback, shifts) { if (!(name in scene_options.defaults)) { scene_options.defaults[name] = defaultvalue; scene_options.validate[name] = validationcallback; if (shifts) { scene_options.shifts.push(name); } } else { scrollmagic._util.log(1, "[static] scrollmagic.scene -> cannot add scene option '" + name + "', because it already exists."); } }; // instance extension function for plugins // todo: doc (private for dev) scrollmagic.scene.extend = function (extension) { var oldclass = this; scrollmagic.scene = function () { oldclass.apply(this, arguments); this.$super = _util.extend({}, this); // copy parent state return extension.apply(this, arguments) || this; }; _util.extend(scrollmagic.scene, oldclass); // copy properties scrollmagic.scene.prototype = oldclass.prototype; // copy prototype scrollmagic.scene.prototype.constructor = scrollmagic.scene; // restore constructor }; /** * todo: docs (private for dev) * @class * @private */ scrollmagic.event = function (type, namespace, target, vars) { vars = vars || {}; for (var key in vars) { this[key] = vars[key]; } this.type = type; this.target = this.currenttarget = target; this.namespace = namespace || ''; this.timestamp = this.timestamp = date.now(); return this; }; /* * todo: docs (private for dev) */ var _util = scrollmagic._util = (function (window) { var u = {}, i; /** * ------------------------------ * internal helpers * ------------------------------ */ // parse float and fall back to 0. var floatval = function (number) { return parsefloat(number) || 0; }; // get current style ie safe (otherwise ie would return calculated values for 'auto') var _getcomputedstyle = function (elem) { return elem.currentstyle ? elem.currentstyle : window.getcomputedstyle(elem); }; // get element dimension (width or height) var _dimension = function (which, elem, outer, includemargin) { elem = (elem === document) ? window : elem; if (elem === window) { includemargin = false; } else if (!_type.domelement(elem)) { return 0; } which = which.charat(0).touppercase() + which.substr(1).tolowercase(); var dimension = (outer ? elem['offset' + which] || elem['outer' + which] : elem['client' + which] || elem['inner' + which]) || 0; if (outer && includemargin) { var style = _getcomputedstyle(elem); dimension += which === 'height' ? floatval(style.margintop) + floatval(style.marginbottom) : floatval(style.marginleft) + floatval(style.marginright); } return dimension; }; // converts 'margin-top' into 'margintop' var _camelcase = function (str) { return str.replace(/^[^a-z]+([a-z])/g, '$1').replace(/-([a-z])/g, function (g) { return g[1].touppercase(); }); }; /** * ------------------------------ * external helpers * ------------------------------ */ // extend obj – same as jquery.extend({}, obja, objb) u.extend = function (obj) { obj = obj || {}; for (i = 1; i < arguments.length; i++) { if (!arguments[i]) { continue; } for (var key in arguments[i]) { if (arguments[i].hasownproperty(key)) { obj[key] = arguments[i][key]; } } } return obj; }; // check if a css display type results in margin-collapse or not u.ismargincollapsetype = function (str) { return ["block", "flex", "list-item", "table", "-webkit-box"].indexof(str) > -1; }; // implementation of requestanimationframe // based on https://gist.github.com/paulirish/1579671 var lasttime = 0, vendors = ['ms', 'moz', 'webkit', 'o']; var _requestanimationframe = window.requestanimationframe; var _cancelanimationframe = window.cancelanimationframe; // try vendor prefixes if the above doesn't work for (i = 0; !_requestanimationframe && i < vendors.length; ++i) { _requestanimationframe = window[vendors[i] + 'requestanimationframe']; _cancelanimationframe = window[vendors[i] + 'cancelanimationframe'] || window[vendors[i] + 'cancelrequestanimationframe']; } // fallbacks if (!_requestanimationframe) { _requestanimationframe = function (callback) { var currtime = new date().gettime(), timetocall = math.max(0, 16 - (currtime - lasttime)), id = window.settimeout(function () { callback(currtime + timetocall); }, timetocall); lasttime = currtime + timetocall; return id; }; } if (!_cancelanimationframe) { _cancelanimationframe = function (id) { window.cleartimeout(id); }; } u.raf = _requestanimationframe.bind(window); u.caf = _cancelanimationframe.bind(window); var loglevels = ["error", "warn", "log"], console = window.console || {}; console.log = console.log || function () {}; // no console log, well - do nothing then... // make sure methods for all levels exist. for (i = 0; i < loglevels.length; i++) { var method = loglevels[i]; if (!console[method]) { console[method] = console.log; // prefer .log over nothing } } u.log = function (loglevel) { if (loglevel > loglevels.length || loglevel <= 0) loglevel = loglevels.length; var now = new date(), time = ("0" + now.gethours()).slice(-2) + ":" + ("0" + now.getminutes()).slice(-2) + ":" + ("0" + now.getseconds()).slice(-2) + ":" + ("00" + now.getmilliseconds()).slice(-3), method = loglevels[loglevel - 1], args = array.prototype.splice.call(arguments, 1), func = function.prototype.bind.call(console[method], console); args.unshift(time); func.apply(console, args); }; /** * ------------------------------ * type testing * ------------------------------ */ var _type = u.type = function (v) { return object.prototype.tostring.call(v).replace(/^\[object (.+)\]$/, "$1").tolowercase(); }; _type.string = function (v) { return _type(v) === 'string'; }; _type.function = function (v) { return _type(v) === 'function'; }; _type.array = function (v) { return array.isarray(v); }; _type.number = function (v) { return !_type.array(v) && (v - parsefloat(v) + 1) >= 0; }; _type.domelement = function (o) { return ( typeof htmlelement === "object" ? o instanceof htmlelement : //dom2 o && typeof o === "object" && o !== null && o.nodetype === 1 && typeof o.nodename === "string"); }; /** * ------------------------------ * dom element info * ------------------------------ */ // 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 var _get = u.get = {}; _get.elements = function (selector) { var arr = []; if (_type.string(selector)) { try { selector = document.queryselectorall(selector); } catch (e) { // invalid selector return arr; } } if (_type(selector) === 'nodelist' || _type.array(selector)) { for (var i = 0, ref = arr.length = selector.length; i < ref; i++) { // list of elements var elem = selector[i]; arr[i] = _type.domelement(elem) ? elem : _get.elements(elem); // if not an element, try to resolve recursively } } else if (_type.domelement(selector) || selector === document || selector === window) { arr = [selector]; // only the element } return arr; }; // get scroll top value _get.scrolltop = function (elem) { return (elem && typeof elem.scrolltop === 'number') ? elem.scrolltop : window.pageyoffset || 0; }; // get scroll left value _get.scrollleft = function (elem) { return (elem && typeof elem.scrollleft === 'number') ? elem.scrollleft : window.pagexoffset || 0; }; // get element height _get.width = function (elem, outer, includemargin) { return _dimension('width', elem, outer, includemargin); }; // get element width _get.height = function (elem, outer, includemargin) { return _dimension('height', elem, outer, includemargin); }; // get element position (optionally relative to viewport) _get.offset = function (elem, relativetoviewport) { var offset = { top: 0, left: 0 }; if (elem && elem.getboundingclientrect) { // check if available var rect = elem.getboundingclientrect(); offset.top = rect.top; offset.left = rect.left; if (!relativetoviewport) { // clientrect is by default relative to viewport... offset.top += _get.scrolltop(); offset.left += _get.scrollleft(); } } return offset; }; /** * ------------------------------ * dom element manipulation * ------------------------------ */ u.addclass = function (elem, classname) { if (classname) { if (elem.classlist) elem.classlist.add(classname); else elem.classname += ' ' + classname; } }; u.removeclass = function (elem, classname) { if (classname) { if (elem.classlist) elem.classlist.remove(classname); else elem.classname = elem.classname.replace(new regexp('(^|\\b)' + classname.split(' ').join('|') + '(\\b|$)', 'gi'), ' '); } }; // if options is string -> returns css value // if options is array -> returns object with css value pairs // if options is object -> set new css values u.css = function (elem, options) { if (_type.string(options)) { return _getcomputedstyle(elem)[_camelcase(options)]; } else if (_type.array(options)) { var obj = {}, style = _getcomputedstyle(elem); options.foreach(function (option, key) { obj[option] = style[_camelcase(option)]; }); return obj; } else { for (var option in options) { var val = options[option]; if (val == parsefloat(val)) { // assume pixel for seemingly numerical values val += 'px'; } elem.style[_camelcase(option)] = val; } } }; return u; }(window || {})); scrollmagic.scene.prototype.addindicators = function () { scrollmagic._util.log(1, '(scrollmagic.scene) -> error calling addindicators() due to missing plugin \'debug.addindicators\'. please make sure to include plugins/debug.addindicators.js'); return this; } scrollmagic.scene.prototype.removeindicators = function () { scrollmagic._util.log(1, '(scrollmagic.scene) -> error calling removeindicators() due to missing plugin \'debug.addindicators\'. please make sure to include plugins/debug.addindicators.js'); return this; } scrollmagic.scene.prototype.settween = function () { scrollmagic._util.log(1, '(scrollmagic.scene) -> error calling settween() due to missing plugin \'animation.gsap\'. please make sure to include plugins/animation.gsap.js'); return this; } scrollmagic.scene.prototype.removetween = function () { scrollmagic._util.log(1, '(scrollmagic.scene) -> error calling removetween() due to missing plugin \'animation.gsap\'. please make sure to include plugins/animation.gsap.js'); return this; } scrollmagic.scene.prototype.setvelocity = function () { scrollmagic._util.log(1, '(scrollmagic.scene) -> error calling setvelocity() due to missing plugin \'animation.velocity\'. please make sure to include plugins/animation.velocity.js'); return this; } scrollmagic.scene.prototype.removevelocity = function () { scrollmagic._util.log(1, '(scrollmagic.scene) -> error calling removevelocity() due to missing plugin \'animation.velocity\'. please make sure to include plugins/animation.velocity.js'); return this; } return scrollmagic; }));