Skip to content

Instantly share code, notes, and snippets.

@rhardih
Created April 18, 2016 14:50
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 rhardih/02b3fa576d55af7153c8f6e83ffd0551 to your computer and use it in GitHub Desktop.
Save rhardih/02b3fa576d55af7153c8f6e83ffd0551 to your computer and use it in GitHub Desktop.
Simple handler class providing callbacks when dom objects scroll into view
var WhenHandler = function(id) {
this.elm = document.querySelector("#" + id);
this.scrolled_into_view = false;
this.scroll_callback;
this.doc = document.documentElement;
this.doc_bounds = this.doc.getBoundingClientRect();
this.elm_bounds = this.elm.getBoundingClientRect();
}
WhenHandler.prototype.scrolls_into_view = function(callback) {
this.scroll_callback = callback;
return this;
}
WhenHandler.prototype.onscroll = function(e) {
if (this.scrolled_into_view) {
return;
}
var bottom = (window.pageYOffset || this.doc.scrollTop) -
(this.doc.clientTop || 0) + this.doc.clientHeight;
if ((this.elm_bounds.bottom + this.elm_bounds.height) < bottom) {
this.scrolled_into_view = true;
this.scroll_callback(this.elm);
}
}
module.exports = function(id) {
var handlers = {};
window.onscroll = function(e) {
for (id in handlers) {
handlers[id].onscroll(e);
}
}
return function(id) {
if(!handlers.hasOwnProperty(id)){
handlers[id] = new WhenHandler(id);
}
return handlers[id];
}
}();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment