Skip to content

Instantly share code, notes, and snippets.

@bibek-magar
Created April 4, 2024 04:08
Show Gist options
  • Save bibek-magar/6af4247e5af77234fbb91a42b8056564 to your computer and use it in GitHub Desktop.
Save bibek-magar/6af4247e5af77234fbb91a42b8056564 to your computer and use it in GitHub Desktop.
Smooth scrolling to section in Vanilla JS
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