There is a simple check to see whether or not an element is in the viewport.
You can choose either to use a plugin or pure JQuery.
Relevant HTML :
<div id="inViewport">Is this in the viewport?</div>
Pure JQuery :
Here is the fiddle for this : http://jsfiddle.net/zWtkc/1/
$.fn.isOnScreen = function(){
var win = $(window);
var viewport = {
top : win.scrollTop(),
left : win.scrollLeft()
};
viewport.right = viewport.left + win.width();
viewport.bottom = viewport.top + win.height();
var bounds = this.offset();
bounds.right = bounds.left + this.outerWidth();
bounds.bottom = bounds.top + this.outerHeight();
return (!(viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top > bounds.bottom));
};
$(document).ready(function(){
$(window).scroll(function(){
if ($('#inViewport').isOnScreen()) {
// The element is visible, do something
alert("in viewport!");
} else {
// The element is NOT visible, do something else
}
});
});
Plugins :
You can use this plugin : https://github.com/teamdf/jquery-visible/
$(document).ready(function(){
if ($('#inViewport').visible(true)) {
// The element is visible, do something
} else {
// The element is NOT visible, do something else
}
});
Or you can use this plugin : http://www.appelsiini.net/projects/viewport which allows for viewport selectors and your code will look like this :
$('#inViewport:in-viewport').doSomething();