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
Did you know?
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#