Detecting if an element is in the viewport using jQuery

How to detect whether my element is within the viewport or not as I scroll the page using jQuery.

You can detect whether an element is within the viewport by comparing the element's position relative to the viewport's dimensions. 
Here's a basic example of how you can achieve this:
function isElementInViewport(el) {
  var elementTop = jQuery(el).offset().top;
  var elementBottom = elementTop + jQuery(el).outerHeight();
  var viewportTop = jQuery(window).scrollTop();
  var viewportBottom = viewportTop + jQuery(window).height();
  return elementBottom > viewportTop && elementTop < viewportBottom;
}

function handleScroll() {
  var element = jQuery('.selector');
  if(element.length) {
    if (isElementInViewport(element[0])) {
      console.log('Element is in viewport');
    } else {
      console.log('Element is not in viewport');
    }
  }
}

jQuery(window).on('scroll', handleScroll);
handleScroll();

Here is the breakdown of the code 👇

isElementInViewport(el) function:

  1. This function takes an element (referred to as el) as an argument.
  2. It calculates the top and bottom coordinates of the element relative to the document using jQuery's .offset() method.
  3. It also calculates the top and bottom coordinates of the viewport (visible area of the browser window) using jQuery's .scrollTop() method to get the current vertical scroll position and .height() method to get the height of the viewport.
  4. It then checks whether the bottom of the element is below the top of the viewport (elementBottom > viewportTop) and whether the top of the element is above the bottom of the viewport (elementTop < viewportBottom). If both conditions are true, it means the element is currently in the viewport, so it returns true; otherwise, it returns false.

handleScroll() function:

  1. This function is called whenever the user scrolls the webpage.
  2. If our element exists, it calls isElementInViewport() with the first matching element as an argument.
  3. Depending on the result, it logs a message to the console indicating whether the element is in the viewport or not.

jQuery(window).on('scroll', handleScroll):

This line attaches an event listener to the scroll event of the window object. Whenever the user scrolls the webpage, the handleScroll() function will be called.


Thank You!