jQuery Is element in viewPort ?
Hi,
a few minutes ago I found the following snippet of code in http://upshots.org/javascript/jquery-test-if-element-is-in-viewport-visible-on-screen.
This snippet is usefull to check if an element is in browser viewport.
$.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));
};
and you can use it like so:
if($('element_selector').isOnScreen())
{
// Do stuff here
}
Written by Merianos Nikos
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Jquery
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#