Detect When An Element Is In The Viewport Using jQuery

File Size: 14.3 KB
Views Total: 484
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   
Detect When An Element Is In The Viewport Using jQuery

A dead simple jQuery script (not a plugin) that determines if an element is in the viewport.

Can be used to detect when an element is scrolling into view and tell the user which part of the page they are viewing.

How to use it:

1. Add the sectionbox class to the elements whose scroll position should be tracked.

<section class="sectionbox" style="background-color: #ddd;">
  <span>0</span>
</section>
<section class="sectionbox">
  <span></span>
</section>
<section class="sectionbox">
  <span></span>
</section>
<section class="sectionbox">
  <span></span>
</section>
<section class="sectionbox">
  <span></span>
</section>

2. Load the required jQuery library in the document. It is always recommended to use the slim build (no animations and AJAX) for better performance.

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

3. The main function that detects the visibility of the elements and do some cool stuff when they're scrolled into view.

(function ($) {
  $(window).on("scroll", function () {
    //Loop Sections
    $(".sectionbox").each(function (i, d) {
      // Get Current Section
      var sec = $(this);
      var el = $(this).find('span');
      if (
        $(this).position().top - 100  <= $(document).scrollTop() &&
        $(this).position().top - 100  + $(this).outerHeight() > $(document).scrollTop()
      ) {
        // when in the viewport
          el.html('<p>'+i+'</p>');
          sec.css({backgroundColor: '#ddd'});
      }else{
        // when out of the viewport
        sec.css({backgroundColor: '#fff'});
      }
    });
  });
})(jQuery);

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