Detect Which Content Section You're Viewing On - r5 Scroll Spy

Detect Which Content Section You're Viewing On - r5 Scroll Spy
File Size: 7.97 KB
Views Total:
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   

A very small jQuery scrollspy plugin that detects which content section your users are viewing on and automatically updates the styles of its corresponding nav link on vertical scrolling.

How to use it:

1. Put the latest jQuery library (slim build) and the jQuery r5 Scroll Spy plugin's script at the end of the document.

<script src="jquery.slim.min.js"></script>
<script src="jquery.r5-scrollspy.js"></script>

2. Create a header navigation that contains anchor links pointing to their corresponding sections.

<header>
  <nav>
    <a href="#intro">Intro</a>
    <a href="#about">About</a>
    ...
  </nav>
</header>
<div id="intro" class="screen">
  Intro
</div>

<div id="about" class="screen">
  About
</div>

...

3. Activate the scrollspy plugin and add the 'active' class to your anchor links when scrolling down.

var $topNavElements = $('header a');
$('.screen').scrollspy({
  outCallback: function ($element) {
    $topNavElements.filter('[href="#' + $element.attr('id') + '"]').removeClass('active');
    $element.find('.side').html('');
  },
  inCallback:  function ($element, side) {
    $topNavElements.filter('[href="#' + $element.attr('id') + '"]').addClass('active');
    $element.find('.side').html(side);
  }
});

4. Apply your own CSS class to the active anchor links:

a.active{
  color: #fff;
  background: #a00;
}

5. Plugin's options with default values.

$('.screen').scrollspy({

  // window, document or any container element
  scrollElement:      window,

  // CSS class added to the section when you're viewing on
  activeClass:        'onScreen',

  // throttle the scroll trigger
  throttle:           250,

  // distance from bottom
  distanceBottom:     3,

  // fraction, pixel or percent
  distanceBottomUnit: 'fraction',

  // in-top, in-bottom, out-top, out-bottom
  addSideClasses:     false,

  // callbacks
  inCallback:         function ($element, side) {
      return true;
  },
  outCallback:        function ($element, side) {
      return true;
  }
  
});

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