Last active
March 16, 2023 13:02
-
-
Save Catevika/f20996d71679e5219b4f085c655b97e0 to your computer and use it in GitHub Desktop.
JS: add active class to a nav item on scroll
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /*============================================= | |
| = Active class on Scroll = | |
| =============================================*/ | |
| const sections = document.querySelectorAll('section'); | |
| const navLinks = document.querySelectorAll('nav ul li a'); | |
| window.addEventListener('scroll', function () { | |
| let currentPos = window.scrollY; | |
| sections.forEach(section => { | |
| let top = section.offsetTop - 60; /* height of the nav */ | |
| let height = section.offsetHeight; | |
| if (currentPos >= top && currentPos < top + height) { | |
| let targetId = section.getAttribute('id'); | |
| navLinks.forEach(link => { | |
| if (link.getAttribute('href') === `#${targetId}`) { | |
| link.classList.add('active'); | |
| } else { | |
| link.classList.remove('active'); | |
| } | |
| }); | |
| } | |
| }); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment