Easy Pure JavaScript Scrollspy Library For Static Webpages – scrollspy.js

Category: Javascript | July 24, 2020
Author:sidsbrmnn
Views Total:319 views
Official Page:Go to website
Last Update:July 24, 2020
License:MIT

Preview:

Easy Pure JavaScript Scrollspy Library For Static Webpages – scrollspy.js

Description:

A lightweight and easy-to-use JavaScript scrollspy plugin that automatically adds or removes the active class from nav links depending on the section you’re viewing on.

Ideal for one-page scroll website that highlights the active item in the navbar when scrolling down or up.

How to use it:

1. Install the scrollspy.js with NPM.

# NPM
$ npm i @sidsbrmnn/scrollspy --save

2. Import the scrollspy as an ES module.

import scrollSpy from '@sidsbrmnn/scrollspy'

3. Or load the scrollspy.min.js in the document.

<script src="/path/to/dist/scrollspy.min.js"></script>

4. Create anchor links pointing to the sections within the document.

<nav>
  <a href="#first">First Section</a>
  <a href="#second">Second Section</a>
  <a href="#last">Last Section</a>
</nav>
<section id="first">
  Section 1
</section>
<section id="first">
  Section 1
</section>
<section id="first">
  Section 1
</section>

5. Initialize the scrollspy and done.

scrollSpy('nav', {
  // options here
});

6. Apply CSS styles to the active menu item.

.active {
  /* CSS styles here */
}

7. Apply a smooth scroll effect to the menu items.

html {
  scroll-behavior: smooth;
  scroll-snap-type: y proximity;
}

8. All default options.

scrollSpy('nav', {
  sectionSelector: 'section',
  targetSelector: 'a',
  offset: 0, // in pixels
  hrefAttribute: 'href',
  activeClass: 'active',
});

You Might Be Interested In:


Leave a Reply