-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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