Jquery check if element is visible in viewport

Vim Bonsu picture Vim Bonsu · Dec 26, 2013 · Viewed 249.5k times · Source

Function to check if the div class "media" is within the browsers visual viewport regardless of the window scroll position.

<HTML>
<HEAD>
  <TITLE>My first HTML document</TITLE>
</HEAD>
<BODY>
  <div class="main">
   <div class="media"></div>
  </div>

</BODY>
</HTML>

Trying to use this plugin https://github.com/customd/jquery-visible with this function but I don't know how to make it work.

$('#element').visible( true );

Answer

ADB picture ADB · Nov 29, 2015

Check if element is visible in viewport using jquery:

First determine the top and bottom positions of the element. Then determine the position of the viewport's bottom (relative to the top of your page) by adding the scroll position to the viewport height.

If the bottom position of the viewport is greater than the element's top position AND the top position of the viewport is less than the element's bottom position, the element is in the viewport (at least partially). In simpler terms, when any part of the element is between the top and bottom bounds of your viewport, the element is visible on your screen.

Now you can write an if/else statement, where the if statement only runs when the above condition is met.

The code below executes what was explained above:

// this function runs every time you are scrolling

$(window).scroll(function() {
    var top_of_element = $("#element").offset().top;
    var bottom_of_element = $("#element").offset().top + $("#element").outerHeight();
    var bottom_of_screen = $(window).scrollTop() + $(window).innerHeight();
    var top_of_screen = $(window).scrollTop();

    if ((bottom_of_screen > top_of_element) && (top_of_screen < bottom_of_element)){
        // the element is visible, do something
    } else {
        // the element is not visible, do something else
    }
});

This answer is a summary of what Chris Bier and Andy were discussing below. I hope it helps anyone else who comes across this question while doing research like I did. I also used an answer to the following question to formulate my answer: Show Div when scroll position.