@webpg/scroll-spy
Version:
Hi guys, welcome to this repository. I created a light-weight Scroll Spy library that you could fully customize with CSS. It's usage is really easy.
2 lines (1 loc) • 2.19 kB
JavaScript
(function(i,e){typeof exports=="object"&&typeof module<"u"?e(exports):typeof define=="function"&&define.amd?define(["exports"],e):(i=typeof globalThis<"u"?globalThis:i||self,e(i["@webpg/scroll-spy"]={}))})(this,function(i){"use strict";var g=Object.defineProperty;var m=(i,e,l)=>e in i?g(i,e,{enumerable:!0,configurable:!0,writable:!0,value:l}):i[e]=l;var d=(i,e,l)=>(m(i,typeof e!="symbol"?e+"":e,l),l);class e{constructor(n){d(this,"duration",500);d(this,"smoothScroll",(n,c=500)=>{const o=window.scrollY;let a=0;const f=(t,r,u,h)=>(t/=h/2,t<1?u/2*t*t+r:(t--,-u/2*(t*(t-2)-1)+r)),s=t=>{a===0&&(a=t);const r=t-a,u=f(r,o,n,c);window.scrollTo(0,u),r<c&&requestAnimationFrame(s)};requestAnimationFrame(s)});d(this,"getMainElement",n=>{if(!n)throw Error("Element does not exist!");return n.hasAttribute("data-wg-link")?n:this.getMainElement(n.parentElement)});d(this,"handleClickOnLinkItem",n=>{var s;n.preventDefault();const o=(s=this.getMainElement(n.target).getAttribute("data-wg-link"))==null?void 0:s.replace("#","");if(!o)throw new Error("section id is not valid!");const a=document.querySelector(`[data-wg-section="${o}"]`);if(!a)throw new Error("section id not found!");const f=a.getBoundingClientRect();this.smoothScroll(Math.ceil(f.top),this.duration)});d(this,"handleUserScroll",n=>{const c=document.querySelectorAll("[data-wg-section]"),o=Array.from(c).find(t=>{const r=t.getBoundingClientRect();if(r.height-Math.abs(r.top)>r.height/2||r.top>0)return t}),a=document.querySelectorAll("[data-wg-link]");Array.from(a).filter(t=>t.getAttribute("data-wg-link")!==`#${o==null?void 0:o.getAttribute("data-wg-section")}`).forEach(t=>t.classList.contains("active")&&t.classList.remove("active"));const s=document.querySelector(`[data-wg-link="#${o.getAttribute("data-wg-section")}"]`);s!=null&&s.classList.contains("active")||s==null||s.classList.add("active")});n&&(this.duration=n);const c=document.querySelectorAll("[data-wg-link]");c&&(document.addEventListener("scroll",this.handleUserScroll),c.forEach((o,a)=>{a===0&&o.classList.add("active"),o.addEventListener("click",this.handleClickOnLinkItem)}))}}i.ScrollSpy=e,Object.defineProperty(i,Symbol.toStringTag,{value:"Module"})});