z2bcha
Last Updated: February 25, 2016
·
1.369K
· merianos

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
}