Simple scrollspy without jQuery, no dependencies

Overview

Simple Scrollspy

NPM version

Simple scrollspy is a lightweight javascript library without jQuery, no dependencies. It is used to make scrollspy effect for your menu, table of contents, etc. Only 1.4Kb.

This is a scrollspy demo for my menu in the navigation bar.

Install

  1. Via NPM:

Install NPM package - https://www.npmjs.com/package/simple-scrollspy:

npm install simple-scrollspy
  1. The other way, you also can inject simple-scrollspy.min.js file into your HTML code:
<script src="/path/to/dist/simple-scrollspy.min.js"></script>

Usages

Easy for using, syntax just like this:

scrollSpy(menuElement, options)

This little plugin will add active class into your existing menu item when you scroll your page to a matched section by ID. If you are giving it a try, make sure that you:

  1. Added CSS for active class in your menu item. Because, this plugin do NOT include CSS.
  2. Added ID for your sections. Example: <section id="first-section">...</section>
  3. Added an attribute which is an section ID into your menu items. Default is href. Example: "href"="#first-section". You also replace href with the other name by hrefAttribute in options.

Arguments

  1. The menuElement is query selector to your menu. It is String or HTMLElement instance.
  2. The options is optional. It is type of Object which contains properties below:
Name Type Default Description
sectionClass String .scrollspy Query selector to your sections
menuActiveTarget String li > a Element will be added active class
offset Number 0 Offset number
hrefAttribute String href The menu item's attribute name which contains section ID
activeClass String active Active class name will be added into menuActiveTarget
scrollContainer String, HTMLElement window User Defined Scrolling Container
smoothScroll Boolean, Object false Enable the smooth scrolling feature
smoothScrollBehavior Function undefined Define your smooth scroll behavior

ES6 example

import scrollSpy from 'simple-scrollspy'

const options = {
  sectionClass: '.scrollspy',           // Query selector to your sections
  menuActiveTarget: '.menu-item',       // Query selector to your elements that will be added `active` class
  offset: 100,                          // Menu item will active before scroll to a matched section 100px
  scrollContainer: '.scroll-container', // Listen scroll behavior on `.scroll-container` instead of `window`
}

// init:
scrollSpy(document.getElementById('main-menu'), options)

// or shorter:
scrollSpy('#main-menu', options)

Inject static file

<script src="/path/to/dist/simple-scrollspy.min.js"></script>
<script>
  window.onload = function () {
    scrollSpy('#main-menu', {
      sectionClass: '.scrollspy',
      menuActiveTarget: '.menu-item',
      offset: 100,
      // smooth scroll
      smoothScroll: true,
      smoothScrollBehavior: function(element) {
        console.log('run "smoothScrollBehavior"...', element)
        element.scrollIntoView({ behavior: 'smooth' }) // default behavior
      }
    })
  }
</script>

Smooth scroll

import jumpTo from 'jump.js'

scrollSpy('#main-menu', {
  // ....,

  // enable smooth scroll:
  // - true: enable with the default scroll behavior
  // - false: disable this feature
  // - object: enable with some options that will pass to `Element.scrollIntoView` or `smoothScrollBehavior`
  //   + Default behavior: https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView
  //   + Jump.js: https://www.npmjs.com/package/jump.js
  smoothScroll: true,

  // customize scroll behavior,
  // - default: Element.scrollIntoView({ ...smoothScroll, behavior: 'smooth' })
  // - customize: you can define your scroll behavior. Ex: use `jump.js`, jQuery, .etc
  smoothScrollBehavior: function(element, options) {
    // use `jump.js` instead of the default scroll behavior
    jumpTo(element, {
      duration: 1000,
      offset: -100,
    })
  }
})

Development

$ yarn install
$ yarn dev

Build

$ yarn build

or:

$ npm run build

The dist folder is automatically created and include file simple-scrollspy.min.js

Note

  • Feel free to make a pull request if you can, and create a Github issue if you come across one.
  • Don't forget to give a star if you feel that the library is helpful to you. It may save somebody a lot of trouble some day.

Helpful links

Licence

MIT

Comments
  • New option offset for section

    New option offset for section

    I have sticky horizontal panel https://skr.sh/sAbFQJdT4g4, but she overlaps my header section https://skr.sh/sAbTtGZONrn. So, need new option offset equals height of this panel.

    opened by projct1 6
  • Feature request: remove active class on first item in nav, when scrolled back up

    Feature request: remove active class on first item in nav, when scrolled back up

    Currently, when scrolling down, active classes are added and removed. Then scrolling back up, the last item (first in the nav) keeps its active class, even if the correponding section is way past it.

    This looks confusing, especially in a page where the content + nav are a bit lower, e.g. below a large hero section. When you scroll back up, and the section is way low, the first item still keeps its active class.

    opened by remcokalf 4
  • Demo not working?

    Demo not working?

    Looks like a file may be missing.

    kimyvgy.github.io/:49 GET https://kimyvgy.github.io/simple-scrollspy/demo/dist/simple-scrollspy.min.js net::ERR_ABORTED 404

    (index):52 Uncaught ReferenceError: scrollSpy is not defined at window.onload ((index):52)

    bug 
    opened by wilr 4
  • refactor: adding a smooth scroll

    refactor: adding a smooth scroll

    Hey man, it's a great script, and it seems to work very well. I would suggest adding a smooth scroll though, because it really gives the viewer a sense of what is going on instead of just checking the browser scrollbar.

    enhancement good first issue 
    opened by noisybird 4
  • FR: Spport for matching window.location.pathname - so multi-page menus with section scroll

    FR: Spport for matching window.location.pathname - so multi-page menus with section scroll

    The code below was used with classic page nav.

        function setActiveUrl(navlinkClass, activeClass) {
    
            navlinkClass = navlinkClass || "nav-link";
            activeClass = activeClass || "active";
    
            var path = window.location.pathname;
            path = path.replace(/\/$/, "");
            path = decodeURIComponent(path);
    
            var navlinks = document.querySelectorAll(`.${navlinkClass}`);
            var activeNavlinks = document.querySelectorAll(`.${navlinkClass} .${activeClass}`);
    
            (activeNavlinks || []).forEach(e => {
                e.classList.remove(activeClass);
            });
    
            (navlinks || []).forEach(e => {
                var href = e.getAttribute("href");
                var isRootMatch = path == "" && href == "/";
                if (href == path || isRootMatch)
                    e.classList.add(activeClass);
                
            });
        }
    
    opened by hidegh 3
  • Horizontal Scrollspy

    Horizontal Scrollspy

    Hello, is there a possibility to detect sections through a horizontal axis and not vertical? I tried to change the values "Top" and "height" by "left" and "width" on the JS file without success. Thank you.

    enhancement 
    opened by ComputerGraphicClub 3
  • Feature Request: User Defined Scrolling Container

    Feature Request: User Defined Scrolling Container

    Allow the user to target other containers that scroll other than the body. I have pulled the master and made some modifications myself, but they are pretty janky and could be done cleaner by the main developer.

    opened by robhuska 3
  • Undocumented necessity: data-scrollspy attribute

    Undocumented necessity: data-scrollspy attribute

    While trying to get the Bootstrap scrollspy plugin to work with a list of anchors with no ordered or unordered lists, I came across this little plugin. Gave it a try but to no avail. But I kept playing with it and discovered an undocumented necessity.

    For the elements (tabs) that will be given the "active" class when scrolling takes place, they all need the "data-scrollspy="#[desired_value]"" attribute. It functions as an href attribute on an anchor; its value must correspond to the value of an element's id on the page. Without this attribute, this plugin won't work at all.

    Somehow this necessary attribute isn't documented. I discovered it while studying the html of the example. Things worked perfectly once I added it to my page.

    Hope this helps.

    opened by Abrahamlet 3
  • adding some functionality for allowing user to define a scrollContainer

    adding some functionality for allowing user to define a scrollContainer

    This is just a simple addition to allow the user to choose a scrolling container other than the body. The code is probably terrible and can be improved, but it works and could be a good start for the main developer to add it.

    opened by robhuska 2
  • feat: add smooth scroll when clicking on a menu item

    feat: add smooth scroll when clicking on a menu item

    This will close #9 by adding options for smooth scrolling feature. For example:

    1. Using via CDN:
    <script src="/path/to/dist/simple-scrollspy.min.js"></script>
    <script>
      window.onload = function () {
        scrollSpy('#main-menu', {
          sectionClass: '.scrollspy',
          menuActiveTarget: '.menu-item',
          offset: 100,
          smoothScroll: true,
        })
      }
    </script>
    
    1. Using with NPM package:
    import jumpTo from 'jump.js'
    
    scrollSpy('#main-menu', {
      // ....,
    
      // enable smooth scroll:
      // - true: enable with the default scroll behavior
      // - false: disable this feature
      // - object: enable with some options that will pass to `window.scroll` or `smoothScrollBehavior`
      //   + Default behavior: https://developer.mozilla.org/en-US/docs/Web/API/Window/scroll
      //   + Jump.js: https://www.npmjs.com/package/jump.js
      smoothScroll: {
        duration: 1000, // only works with jump.js,
        offset: -100,   // only works with jump.js,
      },
    
      // customize scroll behavior,
      // - default: window.scroll({ behavior: 'smooth', ...smoothScroll })
      // - customize: you can define your scroll behavior. Ex: use `jump.js`, jQuery, .etc
      smoothScrollBehavior: function(element, options) {
        // use `jump.js` instead of the default scroll behavior
        jumpTo(element, options)
      }
    })
    
    opened by kimyvgy 1
  • Remove

    Remove "dist" folder and package-lock.json

    The "dist" folder will make conflict. It need to be stored as attachment on specify release version.

    1. Remove dist folder
    2. Update instruction in README.md
    3. Attach dist files into Release
    opened by kimyvgy 1
Releases(v2.3.3)
Owner
Nguyen Huu Kim
Fullstack Software Engineer at Sun* Vietnam, working on Viblo.asia
Nguyen Huu Kim
A ScrollSpy library for detecting enter/exit of elements in the viewport when the user scrolls

jquery-scrollspy A jQuery plugin for detecting enter/exit of elements in the viewport when the user scrolls. New Features Added a couple new features:

John Smart 276 Jul 1, 2022
ScrollSpy in pure JavaScript

VanillaJS ScrollSpy ScrollSpy in pure JavaScript. Browser Support IE 10+ ✔ Latest ✔ Latest ✔ Latest ✔ Latest ✔ Installation $ npm install vanillajs-sc

Eder Sampaio 46 Dec 13, 2022
🖼 Simple file-upload utility that shows a preview of the uploaded image. Written in TypeScript. No dependencies. Works well with or without a framework.

file-upload-with-preview ?? Simple file-upload utility that shows a preview of the uploaded image. Written in TypeScript. No dependencies. Works well

John Datserakis 427 Dec 26, 2022
A simple Node.js code to get unlimited instagram public pictures by every user without api, without credentials.

Instagram Without APIs Instagram Scraping in August 2022, no credentials required This is a Node.js library, are you looking for the same in PHP? go t

Francesco Orsi 28 Dec 29, 2022
Json-parser - A parser for json-objects without dependencies

Json Parser This is a experimental tool that I create for educational purposes, it's based in the jq works With this tool you can parse json-like stri

Gabriel Guerra 1 Jan 3, 2022
NodeJS library without any external dependencies to check if free HTTP/SOCKS4/SOCKS5 proxies are working/up

free-proxy_checker NodeJS library WITHOUT any external dependencies to: download free proxies; check if free HTTP/SOCKS4/SOCKS5 proxies are working/up

antoine vastel 15 Nov 6, 2022
Responsive navigation plugin without library dependencies and with fast touch screen support.

Responsive Nav Responsive navigation plugin without library dependencies and with fast touch screen support. Responsive Nav is a tiny JavaScript plugi

Viljami Salminen 4.1k Dec 29, 2022
Flat and simple color-picker library. No dependencies, no jquery.

Flat and simple color-picker Fully Featured demo Features Simple: The interface is straight forward and easy to use. Practical: Multiple color represe

Ivan Matveev 15 Nov 14, 2022
Calculating Pi number without limitation until 10k digits or more in your browser powered by JS without any third party library!

PI Calculator Web JS (Online) Calculating Pi number without limitation until 10k digits or more in your browser powered by JS without any third party

Max Base 6 Jul 27, 2022
A simple javascript utility library to include partial html (iframe alternate) without a framework or jQuery.

alt-iframe A simple javascript utility library to include partial html (iframe alternate) without a framework or jQuery. <!doctype html> <html lang="e

FrontEndNeo 17 Dec 30, 2022
Simple customizable slide panel (without jQuery)

toolslide.js Minimalistic customizable slide panel (without jQuery) Table of contents Quick start Usage Examples Options Methods Events Browser suppor

null 5 May 23, 2022
Responsive no-jQuery pure JS/CSS Lightbox for images, no dependencies, 10kb unminified source code, with demo

img-lightbox Responsive no-jQuery pure JS/CSS Lightbox for images, no dependencies, 10kb unminified source code, with demo Demo codepen jsfiddle jsbin

englishextra 12 Jun 13, 2022
Creates a table of contents in a DOM element optionally linked to with anchors. No jQuery or other dependencies.

HTML-Contents Creates a table of contents in a DOM element optionally linked to with anchors. No dependencies. @psalmody Get It We're on npm: npm i ht

Michael Tallino 3 Oct 25, 2022
Simple and lightweight form validation for Svelte with no dependencies.

Svelidate Simple and lightweight form validation for Svelte with no dependencies Installation // npm npm install svelidate // yarn yarn add svelidate

null 28 Dec 28, 2022
Popup without jQuery

popup.js Popup without jQuery Demos https://ohno.github.io/popup.js/ CDN <script src="https://cdn.jsdelivr.net/gh/ohno/[email protected]/popup.min.js"></

Shuhei Ohno 2 Mar 24, 2022
Easy and flexible jQuery tabbed functionality without all the styling.

JQuery EasyTabs Plugin Tabs with(out) style. EasyTabs creates tabs with all the functionality, no unwanted changes to your markup, and no hidden styli

Steve Schwartz 553 Nov 23, 2022
A lightweight, powerful and highly extensible templating engine. In the browser or on Node.js, with or without jQuery.

JsRender: best-of-breed templating Simple and intuitive, powerful and extensible, lightning fast For templated content in the browser or on Node.js (w

Boris Moore 2.7k Jan 2, 2023
A jquery plugin that makes images truly responsive, without sacrificing anyone's face. Give it more stars!

Responsify.js A jquery plugin that makes images truly responsive, without sacrificing anyone's face :D When images are used in a responsive container

Wenting Zhang 1.3k Dec 14, 2022
Responsive tabs-to-accordion script without jQuery, written using pure JavaScript

vanilla-tabs Responsive tabs-to-accordion script without jQuery, written using pure JavaScript Author Dmytro Kudleichuk LinkedIn GitHub Online Demo Se

Dmitriy Kudleichuk 7 Dec 20, 2022