Simple ScrollSpy Plugin With Pure JavaScript

Category: Javascript , Menu & Navigation | May 11, 2018
Author: huukimit
Views Total: 62
Official Page: Go to website
Last Update: May 11, 2018
License: MIT

Preview:

Simple ScrollSpy Plugin With Pure JavaScript

Description:

A simple, lightweight JavaScript library that applies the Scrollspy functionality to one page scrolling website.

The plugin automatically adds the CSS class ‘active’ to the navigation item when the page is scrolled to its corresponding section.

How to use it:

Install the library.

# Yarn
$ yarn add simple-scrollspy

# NPM
$ npm install simple-scrollspy --save

Or download the zip and then insert the JavaScript file ‘simple-scrollspy.js’ into the document.

<script src="simple-scrollspy.js"></script>

Create a regular navigation menu and specify the target page sections using the ‘data-scrollspy’ attribute as follows:

<section class="scrollspy" id="home">
  <nav class="navigation">
    <ul id="menu" class="menu">
      <li class="menu__item">
          <a href="#home" class="active" data-scrollspy="#home">Home</a>
      </li>
      <li class="menu__item">
          <a href="#contact" data-scrollspy="#contact">Contact</a>
      </li>
      <li class="menu__item">
          <a href="#about" data-scrollspy="#about">About</a>
      </li>
    </ul>
  </nav>
</section>

<section class="scrollspy" id="contact">
  Contact Setion
</section>

<section class="scrollspy" id="about">
  About Setion
</section>

Active the scrollspy plugin with default options.

window.onload = function () {
  scrollSpy('#menu')
}

All possible options to customize the scrollspy functionality.

window.onload = function () {
  scrollSpy('#menu', {
    offset: 0, // in pixels
    menuActiveTarget: 'li > a',
    sectionClass: '.scrollspy',
    activeClass: 'active',
  })
}

Customize the styles when a menu item is active.

.menu__item a.active {
  color: #ff7600;
  font-weight: bolder;
}

Leave a Reply