Features
-
No dependencies
Written in plain JavaScript, using ES6. Doesn't require any external library or framework.
-
Easy to use
Just include the script in your page and initialize it. The items in your menu will get active class when the section referenced in your anchor is visible.
-
Lightweight and fast
Really small footprint and uses
requestAnimationFrame
to monitor scroll position.
Usage
-
Include MenuSpy
<script src="menuspy.js"></script>
MenuSpy
will be available in the global scope.
Or install with NPM/Yarn and require as a module
NPM
npm install menuspy
Yarn
npm install menuspy
var MenuSpy = require('menuspy');
-
Initialize the plugin on your menu element
<header id="main-header"> <nav> <ul> <li><a href="#features">Features</a></li> <li><a href="#usage">Usage</a></li> <li><a href="#options">Options</a></li> <li><a href="#examples">Examples</a></li> </ul> </nav> </header>
You can also use data-target on the anchor element with a selector. Example:
<a href="#anything" data-target="selector">Anything</a>
var elm = document.querySelector('#main-header'); var ms = new MenuSpy(elm);
The
MenuSpy()
constructor accepts two arguments: the container element and an options object.
Options
You can pass options as the second parameter on plugin initialization. For example:
var elm = document.querySelector('#main-header');
var ms = new MenuSpy(elm, {
activeClass: 'current-item'
});