Cover by Cody Lindley

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo

6.5. Determining Whether an Element Is Within the Viewport

Problem

You want to determine whether an element is visible within the viewport; further, you want to determine the percentage of the element that is visible and scroll to it if it is less than 50 percent visible.

Solution

This makes use of several of the methods discussed in earlier sections of this chapter.

There are several steps to this process:

  1. Determine the size of the viewport.

  2. Determine the scroll position of the document.

  3. Figure out the minimum and maximum values for the top and left positions of the element if the element is visible.

  4. Test the position of the element against those values.

jQuery(document).ready(function() {
    var viewportWidth = jQuery(window).width(),
        viewportHeight = jQuery(window).height(),

        documentScrollTop = jQuery(document).scrollTop(),
        documentScrollLeft = jQuery(document).scrollLeft(),

        minTop = documentScrollTop,
        maxTop = documentScrollTop + viewportHeight,
        minLeft = documentScrollLeft,
        maxLeft = documentScrollLeft + viewportWidth,

        $myElement = jQuery('#myElement'),
        elementOffset = $myElement.offset();
    if (
        (elementOffset.top > minTop && elementOffset.top < maxTop) &&
        (elementOffset.left > minLeft &&elementOffset.left < maxLeft)
    ) {
        alert('element is visible');
    } else {
        alert('element is not visible');
    }
});

With this solution, we know whether the top of the element is visible in the viewport; a better solution would test whether the entire element was contained in the viewport:

jQuery(document).ready(function() ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required