Created
April 4, 2024 04:08
-
-
Save bibek-magar/6af4247e5af77234fbb91a42b8056564 to your computer and use it in GitHub Desktop.
Smooth scrolling to section in Vanilla JS
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
function clickHandler(e) { | |
e.preventDefault() | |
const href = this.getAttribute('href') | |
const offsetTop = document.querySelector(href).offsetTop | |
scroll({ | |
top: offsetTop - 90, | |
behavior: 'smooth', | |
}) | |
} | |
// Usage (Make sure these are implemented after DOMContentLoaded | |
const links = document.querySelectorAll('.nav-link a') | |
for (const link of links) { | |
link.addEventListener('click', clickHandler) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment