Check element visibility with Javascript

The following function checks if a given element is within browser’s viewport:

1
2
3
4
5
6
7
8
9
10
function isScrolledIntoView(elem)
{
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();

    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + $(elem).height();

    return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom));
}

Sample Usage

On this example I’ll be loading iframes only when they are on the browsers viewport. For this to work I initially printed all iframe’s without the SRC attribute. Instead, I used the REL attribute as a placeholder for the iframe destination:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
    var my_interval = setInterval(checkIframesVisibility, 1000);

    function checkIframesVisibility()
    {
        $("iframe").each(function(i) {
            if (isScrolledIntoView($(this)))
            {
                if ($(this).attr('src') == "")
                {
                    $(this).attr('src', $(this).attr('rel'));
                    $(this).iframeAutoHeight({debug: false, diagnostics: false});
                }
            }
        });
    }

    function isScrolledIntoView(elem)
    {
        var docViewTop = $(window).scrollTop();
        var docViewBottom = docViewTop + $(window).height();

        var elemTop = $(elem).offset().top;
        var elemBottom = elemTop + $(elem).height();

        return ((elemBottom <= docViewTop) && (elemTop <= docViewBottom));
    }

PS: The iframeAutoHeight is a plugin that auto resizes the iframe to the content’s height.

Hope you find this is useful!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>