Tiny ScrollSpy & Scroll Progress Indicator In JavaScript – Scroll Progress

Category: Javascript | October 25, 2020
Author:eabrega
Views Total:9 views
Official Page:Go to website
Last Update:October 25, 2020
License:MIT

Preview:

Tiny ScrollSpy & Scroll Progress Indicator In JavaScript – Scroll Progress

Description:

Scroll Progress is a tiny and feature-rich scrollspy library that updates nav items to indicate on which content you’re viewing and displays how much content has been read (as a percentage) in this content section.

How to use it:

1. Create nav links pointing to the sections.

<nav id="home">
  <div id="cursor"></div>
  <menu>
    <a href="#link1">Paragraph A</a>
    <a href="#link2">Paragraph B</a>
    <a href="#link3">Paragraph C</a>
  </menu>
</nav>
<h1 id="link1">Paragraph A</h1>
<h1 id="link2">Paragraph B</h1>
<h1 id="link3">Paragraph C</h1>

2. Create a container to hold scroll position information.

<status>
  <span id="current-paragraph-name"></span>
  <span id="current-paragraph-percent"></span>
</status>

3. Load the Scroll Progress library on the page.

<script src="scroll-progress.min.js"></script>

4. Enable the scrollspy functionality and scroll progress indicator.

document.addEventListener("DOMContentLoaded", function (event) {
  let currentParagraphName = document.getElementById('current-paragraph-name');
  let currentParagraphPercent = document.getElementById('current-paragraph-percent');
  new ScrollProgress.Init(
      "#cursor",
      "menu",
      progress => {
          currentParagraphName.innerText = document.getElementById(progress.id).innerText;
          currentParagraphPercent.innerText = progress.percent + '%';
      },
      id => {
          document.querySelectorAll('a[href*="link"]').forEach(element => element.classList.remove('active-meny-item'));
          document.querySelector(`[href="#${id}"]`).classList.add('active-meny-item');
      }
  );
});

Changelog:

v1.2.0 (10/25/2020)

  • bug fixed and opimize

You Might Be Interested In:


Leave a Reply