Highlight Active Menu Item On Page Scroll – MenuSpy.js

Category: Javascript , Menu & Navigation , Recommended | September 13, 2018
Views Total:12,511 views
Official Page:Go to website
Last Update:September 13, 2018


Highlight Active Menu Item On Page Scroll – MenuSpy.js


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.


# Yarn
$ yarn add menuspy
$ 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">
      <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>
  <section id="home">
    <div class="inner">
  <section id="section-1">
    <div class="inner">
      <h2>Section 1</h2>
  <section id="section-2">
    <div class="inner">
      <h2>Section 2</h2>
  <section id="section-3">
    <div class="inner">
      <h2>Section 3</h2>

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



  • v1.3.0

You Might Be Interested In:

Leave a Reply