Check Whether A DOM Element Is Visible Using jQuery

File Size: 4.4 KB
Views Total: 278
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   
Check Whether A DOM Element Is Visible Using jQuery

A super tiny jQuery script that calculates the position of an element from the top of the page and then executes custom functions when the element becomes visible/invisible on scroll.

How to use it:

1. Load the necessary jQuery library in the document.

<script src="/path/to/cdn/jquery.slim.min.js"></script>

2. The main function to detect if an element is visible/invisible.

let scrollTop = $(this).scrollTop();
function domElemDetector(el) {
  if ($(el).length) {
    let elemOffsetTop = el.offset().top
    let elemHeight = el.outerHeight();
    let windowHeight = $(window).outerHeight();
    if (scrollTop >= (elemOffsetTop - (windowHeight / 2))) {
      // do some cool stuff when the element is visible
    } else {
      // do some cool stuff when the element is invisible
    }
  }
}

3. Apply the DOM Element Detector to your element.

<div class="element">
  ...
</div>
domElemDetector($('.element'));

4. Enable the DOM Element Detector on page scroll.

$(document).ready(function () {
  $(function () {
    $(window).on('scroll', function () {
      let scrollTop = $(this).scrollTop();
      function domElemDetector(el) {
        if ($(el).length) {
          let elemOffsetTop = el.offset().top
          let elemHeight = el.outerHeight();
          let windowHeight = $(window).outerHeight();
          if (scrollTop >= (elemOffsetTop - (windowHeight / 2))) {
            // do some cool stuff when the element is visible
          } else {
            // do some cool stuff when the element is invisible
          }
        }
      }
      domElemDetector($('.element'));
    });
  });
});

This awesome jQuery plugin is developed by kawsarBinSiraj. For more Advanced Usages, please check the demo page or visit the official website.