Detect Which Page Section Is In The Viewport - jQuery sectionInView

File Size: 9.76 KB
Views Total: 136
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   
Detect Which Page Section Is In The Viewport - jQuery sectionInView

sectionInView is a tiny jQuery is in viewport plugin that detects if a section of your page is visible in the viewport or hidden below the fold.

How to use it:

1. Download and place the main script sectionInView.min.js after jQuery.

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

2. Initialize the sectionInView plugin on your page sections and do some cool stuff. In the example below, you will see that the background color of the page section, which is in the viewport, will change and, at the same time, add a CSS class to the corresponding menu item.

<nav>
  <a href="#section-1">Section One</a>
  <a href="#section-2">Section Two</a>
  <a href="#section-3">Section Three</a> 
</nav>
<div class="container">
  <section id="section-1">
    <h2>Section One</h2>
  </section>
  <section id="section-2">
    <h2>Section Two</h2>
  </section>
  <section id="section-3">
    <h2>Section Three</h2>
  </section>
</div>
$("section").sectionInView(
  function (sectionId) {
    // is in the viewport
    $('section#' + sectionId +'').css("background-color", "yellow");
    $('a[href$="'+ sectionId +'"]').closest('li').addClass('active');
  },
  function (sectionId) {
    // is out of the viewport
    $('a[href$="'+ sectionId +'"]').closest('li').removeClass('active');
  },
  {
    offset: 200 // top offset in px
  }
);

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