Update Navigation Items Based On Scroll Position – ScrollSpy.js

Category: Javascript , Menu & Navigation | November 18, 2019
Author:erfanmola
Views Total:3,175 views
Official Page:Go to website
Last Update:November 18, 2019
License:MIT

Preview:

Update Navigation Items Based On Scroll Position – ScrollSpy.js

Description:

A small pure JavaScript scrollspy library that automatically highlights navigation items based upon scroll position to indicate which content section is currently active in the viewport.

Ideal for creating a floating table of contents (in-page navigation) for your long web page that activates the links based on the scroll position of the content for the navigation link.

The library also provides a smooth scroll functionality that enables the visitor to smoothly scroll through content sections by clicking the links in the navigation.

How to use it:

1. Insert the stylesheet ScrollSpy.min.css and JavaScript ScrollSpy.min.js into the document.

<link rel="stylesheet" href="ScrollSpy.min.css" />
<script src="ScrollSpy.min.js"></script>

2. Add the CSS class .scrollspy to the content sections and define the section name in the spy-title attribute.

<section class="scrollspy" spy-title="Section 1">
  Section 1
</section>
<section class="scrollspy" spy-title="Section 2">
  Section 2
</section>
<section class="scrollspy" spy-title="Section 3">
  Section 3
</section>
...

3. Create a container to hold the table of contents (in-page navigation).

<div id="indicator"></div>

4. Enable the scrollspy functionality.

var spy = new ScrollSpy();

5. Generate links in the table of contents (in-page navigation).

var indicator = document.getElementById('indicator');
spy.Indicator({
  element: indicator
});

6. Override the default CSS selector. Default: ‘scrollspy’.

var spy = new ScrollSpy({
    contexts_class: 'scrollspy'
});

7. Set the time to wait between detecting scrolls. Default: 200ms.

var spy = new ScrollSpy({
    delay: 100
});

8. Event handlers.

var spy = new ScrollSpy({
    allbackOnChange: function callbackOnChange() {
      // called on each change
    },
    callbackOnDestroy: function callbackOnDestroy() {
      // called on destroy
    }
});

9. Customize the table of contents (in-page navigation).

spy.Indicator({
  element: null,
  indicator_container_class: '',
  indicator_item_class: '',
  clickable: true,
  forceActive: false
});

You Might Be Interested In:


Leave a Reply