Skip to content

Instantly share code, notes, and snippets.

@motionharvest
Last active December 23, 2015 20:39
Show Gist options
  • Save motionharvest/6691295 to your computer and use it in GitHub Desktop.
Save motionharvest/6691295 to your computer and use it in GitHub Desktop.
Simple jQuery plugin for giving an element a class when it is scrolled into view
//detect if an object is on the screen or not.
(function($){
var t = 0,
ot,
off,
oh,
selectors = [],
$d = $(document),
$w = $(window),
wh = $w.height(),
tmp, tmps;
//on scroll - loop through elements
// if they have an onscreen-offset grab it
// if the element is on the screen, give it it's class
// if its off, take it's class away
$d.on('scroll', function(e){
t = $d.scrollTop();
for(var k = 0; k < selectors.length; k++){
tmp = selectors[k][0];
tmps = selectors[k][1];
ot = tmp.offset().top;
oh = tmp.height();
off = tmp.attr('data-onscreen-offset') || 0; //how much on the screen before we apply the class
if(ot < (t - off) + wh && ot + oh > t ){
if(!tmp.hasClass(tmps)){
tmp.addClass(tmps);
}
}else{
if(tmp.hasClass(tmps)){
tmp.removeClass(tmps);
}
}
}
});
//on resize - update window height reference
//and trigger scroll
$w.on('resize', function(){
wh = $w.height();
$d.trigger('scroll');
})
//when selector is used, the element and the class name are pushed
//into selectors
$.fn.cssOnScreen = function(style){
selectors.push([$(this), style]);
$d.trigger('scroll');
};
})(jQuery);
<div id="lifter" data-onscreen-offset="400">
<img src="img/lifter.png">
</div>
<script>
$('#lifter').cssOnScreen('activate');
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment