Skip to content

Instantly share code, notes, and snippets.

@uschmelzer
Forked from eltonmesquita/onViewport.js
Created June 15, 2017 19:46
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 uschmelzer/bad1327e6fbc525e98556d8d1f050b51 to your computer and use it in GitHub Desktop.
Save uschmelzer/bad1327e6fbc525e98556d8d1f050b51 to your computer and use it in GitHub Desktop.
A simple jQuery function that adds a class when the target(s) is in the viewport
function onViewport(el, elClass, offset, callback) {
/*** Based on http://ejohn.org/blog/learning-from-twitter/ ***/
var didScroll = false;
var this_top;
var height;
var top;
if(!offset) { var offset = 0; }
$(window).scroll(function() {
didScroll = true;
});
setInterval(function() {
if (didScroll) {
didScroll = false;
top = $(this).scrollTop();
$(el).each(function(i){
this_top = $(this).offset().top - offset;
height = $(this).height();
// Scrolled within current section
if (top >= this_top && !$(this).hasClass(elClass)) {
$(this).addClass(elClass);
if (typeof callback == "function") callback(el);
}
});
}
}, 100);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment