Skip to content

Instantly share code, notes, and snippets.

@hlaporthein
Forked from eltonmesquita/onViewport.js
Created March 29, 2018 00:31
Show Gist options
  • Select an option

  • Save hlaporthein/3185e77b341d80c590dad53b0cd5e4a3 to your computer and use it in GitHub Desktop.

Select an option

Save hlaporthein/3185e77b341d80c590dad53b0cd5e4a3 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