/*jslint browser: true, indent: 4 */ (function (g) { "use strict"; var ScrollGuard, started = false, lock = false, timer, breakpoints = [], getDocHeight, getScrollTop; // found at http://james.padolsey.com/javascript/ // get-document-height-cross-browser/ getDocHeight = function () { return Math.max( Math.max(document.body.scrollHeight, document.documentElement.scrollHeight), Math.max(document.body.offsetHeight, document.documentElement.offsetHeight), Math.max(document.body.clientHeight, document.documentElement.clientHeight) ); }; // found at http://stackoverflow.com/questions/871399/ // cross-browser-method-for-detecting-the-scrolltop-of-the-browser-g getScrollTop = function () { var b, d; if (g.pageYOffset !== undefined) { return g.pageYOffset; } b = document.body; d = document.documentElement; d = (d.clientHeight) ? d : b; return d.scrollTop; }; ScrollGuard = { // from: a distance from top, given in pixels (required) // to: a distance from top, given in pixels (optional) // // special cases: // from = -1 will instead look if bottom of page // is visible. add: function (callback, from, to) { var range; if (from === -1) { range = function (topPos) { return getDocHeight() - topPos <= g.innerHeight; }; } else { if (to === undefined) { range = function (topPos) { return topPos >= from; }; } else { range = function (topPos) { return topPos >= from && topPos <= to; }; } } breakpoints.push({ within: range, callback: callback }); }, fire: function (pos) { var max = breakpoints.length, i, bp; lock = true; for (i = 0; i < max; i += 1) { bp = breakpoints[i]; if (bp.within(pos)) { bp.callback(); } } lock = false; }, start: function () { if (started) { return; } var callback = function () { if (lock === false) { clearTimeout(timer); timer = setTimeout(function () { ScrollGuard.fire(getScrollTop()); }, 100); } }; if (g.attachEvent) { g.attachEvent('onscroll', callback); } else { g.addEventListener('scroll', callback, false); } started = true; // initial call to catch initial scroll positions callback(); } }; g.ScrollGuard = ScrollGuard; }(this));