Created
April 26, 2021 02:08
-
-
Save steveshead/3e17a27fabbd8f8d5032dfd9f235a1f5 to your computer and use it in GitHub Desktop.
[Javascript - Highlight nav item on scroll ] - vanilla javascript scroll spy
This file contains 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
window.addEventListener('DOMContentLoaded', () => { | |
const observer = new IntersectionObserver(entries => { | |
entries.forEach(entry => { | |
const id = entry.target.getAttribute('id'); | |
if (entry.intersectionRatio > 0) { | |
document.querySelector(`nav li a[href="#${id}"]`).parentElement.classList.add('active'); | |
} else { | |
document.querySelector(`nav li a[href="#${id}"]`).parentElement.classList.remove('active'); | |
} | |
}); | |
}); | |
// Track all sections that have an `id` applied | |
document.querySelectorAll('section[id]').forEach((section) => { | |
observer.observe(section); | |
}); | |
}); | |
// Assumption is you have set up anchors on a Bootstrap like nav element |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment