/*! jquery waypoints - v1.0.2 copyright (c) 2011 caleb troughton dual licensed under the mit license and gpl license. https://github.com/imakewebthings/jquery-waypoints/blob/master/mit-license.txt https://github.com/imakewebthings/jquery-waypoints/blob/master/gpl-license.txt */ /* waypoints is a small jquery plugin that makes it easy to execute a function whenever you scroll to an element. github repository: https://github.com/imakewebthings/jquery-waypoints documentation and examples: http://imakewebthings.github.com/jquery-waypoints changelog: v1.0.2 - moved scroll and resize handler bindings out of load. should play nicer with async loaders like head js and labjs. - fixed a 1px off error when using certain % offsets. - added unit tests. v1.0.1 - added $.waypoints('viewportheight'). - fixed ios bug (using the new viewportheight method). - added offset function alias: 'bottom-in-view'. v1.0 - initial release. support: - jquery versions 1.4+ - ie6+, ff3+, chrome 6+, safari 4+, opera 11 - other versions and browsers may work, these are just the ones i've looked at. */ (function($, wp, wps, window, undefined){ '$:nomunge'; var $w = $(window), /* list of all elements that have been registered as waypoints. used privately. each object in the array contains: element: jquery object containing a single html element. offset: the window scroll offset, in px, that triggers the waypoint event. options: options object that was passed to the waypoint fn function. */ waypoints = [], /* starting at a ridiculous negative number allows for a 'down' trigger of 0 or negative offset waypoints on load. useful for setting initial states. */ oldscroll = -99999, // flags used in throttling. didscroll = false, didresize = false, // keeping common strings as variables = better minification eventname = 'waypoint.reached', methods = { /* jquery.fn.waypoint([handler], [options]) handler function, optional a callback function called when the user scrolls past the element. the function signature is function(event, direction) where event is a standard jquery event object and direction is a string, either 'down' or 'up' indicating which direction the user is scrolling. options object, optional a map of options to apply to this set of waypoints, including where on the browser window the waypoint is triggered. for a full list of options and their defaults, see $.fn.waypoint.defaults. this is how you register an element as a waypoint. when the user scrolls past that element it triggers waypoint.reached, a custom event. since the parameters for creating a waypoint are optional, we have a few different possible signatures. let’s look at each of them. someelements.waypoint(); calling .waypoint with no parameters will register the elements as waypoints using the default options. the elements will fire the waypoint.reached event, but calling it in this way does not bind any handler to the event. you can bind to the event yourself, as with any other event, like so: someelements.bind('waypoint.reached', function(event, direction) { // make it rain }); you will usually want to create a waypoint and immediately bind a function to waypoint.reached, and can do so by passing a handler as the first argument to .waypoint: someelements.waypoint(function(event, direction) { if (direction === 'down') { // do this on the way down } else { // do this on the way back up through the waypoint } }); this will still use the default options, which will trigger the waypoint when the top of the element hits the top of the window. we can pass .waypoint an options object to customize things: someelements.waypoint(function(event, direction) { // do something amazing }, { offset: '50%' // middle of the page }); you can also pass just an options object. someelements.waypoint({ offset: 100 // 100px from the top }); this behaves like .waypoint(), in that it registers the elements as waypoints but binds no event handlers. calling .waypoint on an existing waypoint will extend the previous options. if the call includes a handler, it will be bound to waypoint.reached without unbinding any other handlers. */ init: function(f, options) { // register each element as a waypoint, add to array. this.each(function() { var $this = $(this), ndx = waypointindex($this), base = ndx < 0 ? $.fn[wp].defaults : waypoints[ndx].options, opts = $.extend({}, base, options); // offset aliases opts.offset = opts.offset === "bottom-in-view" ? function() { return $[wps]('viewportheight') - $(this).outerheight(); } : opts.offset; // update, or create new waypoint if (ndx < 0) { waypoints.push({ element: $this, offset: $this.offset().top, options: opts }); } else { waypoints[ndx].options = opts; } // bind the function if it was passed in. f && $this.bind(eventname, f); }); // need to resort+refresh the waypoints array after new elements are added. $[wps]('refresh'); return this; }, /* jquery.fn.waypoint('remove') passing the string 'remove' to .waypoint unregisters the elements as waypoints and wipes any custom options, but leaves the waypoint.reached events bound. calling .waypoint again in the future would reregister the waypoint and the old handlers would continue to work. */ remove: function() { return this.each(function() { var ndx = waypointindex($(this)); if (ndx >= 0) { waypoints.splice(ndx, 1); } }); }, /* jquery.fn.waypoint('destroy') passing the string 'destroy' to .waypoint will unbind all waypoint.reached event handlers on those elements and unregisters them as waypoints. */ destroy: function() { return this.unbind(eventname)[wp]('remove'); } }; /* given a jquery element, returns the index of that element in the waypoints array. returns the index, or -1 if the element is not a waypoint. */ function waypointindex(el) { var i = waypoints.length - 1; while (i >= 0 && waypoints[i].element[0] !== el[0]) { i -= 1; } return i; } /* for the waypoint and direction passed in, trigger the waypoint.reached event and deal with the triggeronce option. */ function triggerwaypoint(way, dir) { way.element.trigger(eventname, dir) if (way.options.triggeronce) { way.element[wp]('destroy'); } } /* function that checks the new scroll value against the old value. if waypoints were reached, fire the appropriate events. called within a throttled window.scroll handler later. */ function doscroll() { var newscroll = $w.scrolltop(), // are we scrolling up or down? used for direction argument in callback. isdown = newscroll > oldscroll, // get a list of all waypoints that were crossed since last scroll move. pointshit = $.grep(waypoints, function(el, i) { return isdown ? (el.offset > oldscroll && el.offset <= newscroll) : (el.offset <= oldscroll && el.offset > newscroll); }); // ios adjustment if (!oldscroll || !newscroll) { $[wps]('refresh'); } // done with scroll comparisons, store new scroll before ejection oldscroll = newscroll; // no waypoints crossed? eject. if (!pointshit.length) return; /* one scroll move may cross several waypoints. if the continuous setting is true, every waypoint event should fire. if false, only the last one. */ if ($[wps].settings.continuous) { $.each(isdown ? pointshit : pointshit.reverse(), function(i, point) { triggerwaypoint(point, [isdown ? 'down' : 'up']); }); } else { triggerwaypoint(pointshit[isdown ? pointshit.length - 1 : 0], [isdown ? 'down' : 'up']); } } /* fn extension. delegates to appropriate method. */ $.fn[wp] = function(method) { if (methods[method]) { return methods[method].apply(this, array.prototype.slice.call(arguments, 1)); } else if (typeof method === "function" || !method) { return methods.init.apply(this, arguments); } else if (typeof method === "object") { return methods.init.apply(this, [null, method]); } else { $.error( 'method ' + method + ' does not exist on jquery' + wp ); } }; /* the default options object that is extended when calling .waypoint. it has the following properties: offset number | string | function default: 0 determines how far the top of the element must be from the top of the browser window to trigger a waypoint. it can be a number, which is taken as a number of pixels, a string representing a percentage of the viewport height, or a function that will return a number of pixels. triggeronce boolean default: false if true, the waypoint will be destroyed when triggered. an offset of 250 would trigger the waypoint when the top of the element is 250px from the top of the viewport. negative values for any offset work as you might expect. a value of -100 would trigger the waypoint when the element is 100px above the top of the window. offset: '100%' a string percentage will determine the pixel offset based on the height of the window. when resizing the window, this offset will automatically be recalculated without needing to call $.waypoints('refresh'). // the bottom of the element is in view offset: function() { return $.waypoints('viewportheight') - $(this).outerheight(); } offset can take a function, which must return a number of pixels from the top of the window. the this value will always refer to the raw html element of the waypoint. as with % values, functions are recalculated automatically when the window resizes. for more on recalculating offsets, see $.waypoints('refresh'). an offset value of 'bottom-in-view' will act as an alias for the function in the example above, as this is a common usage. offset: 'bottom-in-view' you can see this alias in use on the scroll analytics example page. the triggeronce flag, if true, will destroy the waypoint after the first trigger. this is just a shortcut for calling .waypoint('destroy') within the waypoint handler. this is useful in situations such as scroll analytics, where you only want to record an event once for each page visit. */ $.fn[wp].defaults = { offset: 0, triggeronce: false }; /* methods used by the jquery object extension. */ var jqmethods = { /* jquery.waypoints('refresh') this will force a recalculation of each waypoint’s trigger point based on its offset option. this is called automatically whenever the window is resized, new waypoints are added, or a waypoint’s options are modified. if your project is changing the dom or page layout without doing one of these things, you may want to manually call this refresh. */ refresh: function() { $.each(waypoints, function(i, o) { // adjustment is just the offset if it's a px value var adjustment = 0, oldoffset = o.offset; // set adjustment to the return value if offset is a function. if (typeof o.options.offset === "function") { adjustment = o.options.offset.apply(o.element); } // calculate the adjustment if offset is a percentage. else if (typeof o.options.offset === "string") { var amount = parsefloat(o.options.offset), adjustment = o.options.offset.indexof("%") ? math.ceil($[wps]('viewportheight') * (amount / 100)) : amount; } else { adjustment = o.options.offset; } /* set the element offset to the window scroll offset, less the adjustment. */ o.offset = o.element.offset().top - adjustment; /* an element offset change across the current scroll point triggers the event, just as if we scrolled past it. */ if (oldscroll > oldoffset && oldscroll <= o.offset) { triggerwaypoint(o, ['up']); } else if (oldscroll < oldoffset && oldscroll >= o.offset) { triggerwaypoint(o, ['down']); } }); // keep waypoints sorted by offset value. waypoints.sort(function(a, b) { return a.offset - b.offset; }); }, /* jquery.waypoints('viewportheight') this will return the height of the viewport, adjusting for inconsistencies that come with calling $(window).height() in ios. recommended for use within any offset functions. */ viewportheight: function() { return (window.innerheight ? window.innerheight : $w.height()); }, /* jquery.waypoints() this will return a jquery object with a collection of all registered waypoint elements. $('.post').waypoint(); $('.ad-unit').waypoint(function(event, direction) { // passed an ad unit }); console.log($.waypoints()); the example above would log a jquery object containing all .post and .ad-unit elements. */ aggregate: function() { var points = $(); $.each(waypoints, function(i, e) { points = points.add(e.element); }); return points; } }; /* jquery object extension. delegates to appropriate methods above. */ $[wps] = function(method) { if (jqmethods[method]) { return jqmethods[method].apply(this); } else { return jqmethods["aggregate"](); } }; /* $.waypoints.settings settings object that determines some of the plugin’s behavior. continuous boolean default: true determines which waypoints to trigger events for if a single scroll change passes more than one waypoint. if false, only the last waypoint is triggered and the rest are ignored. if true, all waypoints between the previous scroll position and the new one are triggered in order. resizethrottle number default: 200 for performance reasons, the refresh performed during window resizes is throttled. this value is the rate-limit in milliseconds between resize refreshes. for more information on throttling, check out ben alman’s throttle / debounce plugin. http://benalman.com/projects/jquery-throttle-debounce-plugin/ scrollthrottle number default: 100 for performance reasons, checking for any crossed waypoints during the window scroll event is throttled. this value is the rate-limit in milliseconds between scroll checks. for more information on throttling, check out ben alman’s throttle / debounce plugin. http://benalman.com/projects/jquery-throttle-debounce-plugin/ */ $[wps].settings = { continuous: true, resizethrottle: 200, scrollthrottle: 100 }; /* bind resize and scroll handlers */ $w.scroll(function() { // throttle the scroll event. see doscroll() for actual scroll functionality. if (!didscroll) { didscroll = true; window.settimeout(function() { doscroll(); didscroll = false; }, $[wps].settings.scrollthrottle); } }).resize(function() { // throttle the window resize event to call jquery.waypoints('refresh'). if (!didresize) { didresize = true; window.settimeout(function() { $[wps]('refresh'); didresize = false; }, $[wps].settings.resizethrottle); } }).load(function() { // calculate everything once on load. $[wps]('refresh'); /* fire a scroll check, should the page be loaded at a non-zero scroll value, as with a fragment id link or a page refresh. */ doscroll(); }); })(jquery, 'waypoint', 'waypoints', this);