Skip to content

Instantly share code, notes, and snippets.

@nathancahill
Created August 27, 2016 18:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nathancahill/a53dc76eeb589817c9abca08219fa959 to your computer and use it in GitHub Desktop.
Save nathancahill/a53dc76eeb589817c9abca08219fa959 to your computer and use it in GitHub Desktop.
function Registry(a){return new inViewRegistry(a)}var throttle=function(a,b){var c=!1;return function(){c||(a.call(),c=!0,setTimeout(function(){c=!1},b))}},inViewport=function(a,b){void 0===b&&(b=0);var c=a.getBoundingClientRect(),d=c.top,e=c.right,f=c.bottom,g=c.left;return f>b&&e>b&&window.innerWidth-g>b&&window.innerHeight-d>b},inViewRegistry=function(b){this.current=[],this.elements=b,this.handlers={enter:[],exit:[]},this.singles={enter:[],exit:[]}};inViewRegistry.prototype.check=function(b){var c=this;return this.elements.forEach(function(a){var d=inViewport(a,b),e=c.current.indexOf(a),f=e>-1,g=d&&!f,h=!d&&f;g&&(c.current.push(a),c.emit("enter",a)),h&&(c.current.splice(e,1),c.emit("exit",a))}),this},inViewRegistry.prototype.on=function(b,c){return this.handlers[b].push(c),this},inViewRegistry.prototype.once=function(b,c){return this.singles[b].unshift(c),this},inViewRegistry.prototype.emit=function(b,c){for(var d=this;this.singles[b].length;)d.singles[b].pop()(c);for(var e=this.handlers[b].length;--e>-1;)d.handlers[b][e](c);return this};var inView=function(){var a=100,b=["scroll","resize","load"],c=0,d={history:[]};b.forEach(function(b){return window.addEventListener(b,throttle(function(){d.history.forEach(function(a){d[a].check(c)})},a))});var e=function(a){if("string"==typeof a){var b=[].slice.call(document.querySelectorAll(a));return d.history.indexOf(a)>-1?d[a].elements=b:(d[a]=Registry(b),d.history.push(a)),d[a]}};return e.offset=function(a){"number"==typeof a&&(c=a)},e.is=inViewport,e}();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment