Highlight Active Menu Item On Page Scroll – MenuSpy.js

Category: Javascript , Menu & Navigation , Recommended | September 13, 2018
Author:lcdsantos
Views Total:12,358 views
Official Page:Go to website
Last Update:September 13, 2018
License:MIT

Preview:

Highlight Active Menu Item On Page Scroll – MenuSpy.js

Description:

MenuSpy.js is a multi-purpose JavaScript library for your one page scrolling website that highlights the menu item relative to the currently visible section.

The goal of this library is to detect the scroll position and add a certain CSS class to active menu items when you scroll past their sections.

Installation:

# Yarn
$ yarn add menuspy
# NPM
$ npm install menuspy --save

How to use it:

Download and insert the main JavaScript file MenuSpy.js into the webpage.

<script src="dist/menuspy.js"></script>

Assuming you have a navigation menu that contains anchor links pointing to the different sections within the document:

<header id="main-header" class="side-menu">
  <nav>
    <ul>
      <li class="active"><a href="#home"><span>Home</span></a></li>
      <li><a href="#section-1"><span>Section 1</span></a></li>
      <li><a href="#section-2"><span>Section 2</span></a></li>
      <li><a href="#section-3"><span>Section 3</span></a></li>
    </ul>
  </nav>
</header>
<main>
  <section id="home">
    <div class="inner">
      <h1>Home</h1>
    </div>
  </section>
  <section id="section-1">
    <div class="inner">
      <h2>Section 1</h2>
    </div>
  </section>
  <section id="section-2">
    <div class="inner">
      <h2>Section 2</h2>
    </div>
  </section>
  <section id="section-3">
    <div class="inner">
      <h2>Section 3</h2>
    </div>
  </section>
</main>

Active the scrollspy functionality on the navigation.

var elm = document.querySelector('#main-header');
var ms = new MenuSpy(elm);

Default options.

var ms = new MenuSpy(elm,{
    // menu selector
    menuItemSelector: 'a[href^="#"]',
    // CSS class for active item
    activeClass   : 'active',
    // amount of space between your menu and the next section to be activated.
    threshold     : 15,
    // enable or disable browser's hash location change.
    enableLocationHash: true,
    // timeout to apply browser's hash location.
    hashTimeout   : 600,
    // called every time a new menu item activates.
    callback      : null
    
});

Changelog:

09/13/2018

  • v1.3.0

You Might Be Interested In:


Leave a Reply