Check if the element is visible in the viewport without a plugin:
First determine the top and bottom positions of the element. Then, determine the position of the bottom of the viewport (relative to the top of your page) by adding the scroll position to the height of the viewport.
If the bottom position of the viewport is greater than the top position of the item AND the top position of the viewport is less than the bottom position of the item, the item is in the viewport (at least partially). Simply put, when any part of an element is between the upper and lower borders of your viewport, the element is visible on your screen.
Now you can write an if / else statement where the if statement is only executed if the above condition is met.
The code below does 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 Beer and Andy discussed below. I hope this helps everyone who comes across this issue doing research like me. I also used the answer to the following question to formulate my answer: Show Div when the scroll position .
ADB Nov 29 '15 at 4:45 2015-11-29 04:45
source share