Simple ScrollSpy Plugin With Pure JavaScript

Category: Javascript , Menu & Navigation | November 28, 2023
Author:kimyvgy
Views Total:8 views
Official Page:Go to website
Last Update:November 28, 2023
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',
    scrollContainer: ''
  })
}

Customize the styles when a menu item is active.

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

Changelog:

v2.4.1 (11/28/2023)

  • Bugfix

v2.4.0 (05/25/2023)

  • Add onActive hook

v2.3.6 (02/23/2023)

  • Support CDN.js by adding dist/simple-scrollspy.min.js to NPM package. CDN.js will auto-fetch dist/simple-scrollspy.min.js to CDN servers.

v2.3.4 (02/13/2023)

  • Bugfixes

09/29/2020

  • feat: adding some functionality for allowing user to define a scrollContainer

v2.0.3 (12/25/2019)

  • fix potential security vulnerabilities issues

02/17/2019

  • Fix: Error is thrown when menu item can not be found

02/16/2019

  • Fix data-scrollspy issue and refactor code

You Might Be Interested In:


Leave a Reply