Pure Vanilla JavaScript Smooth Scroll to Element on <a> anchor tag click #id
It took me half an hour and countless of stackoverflow pages to find a perfect solution for a smooth scroll for <a> anchor links.
So I'm adding here it as a snippet for future googlers.
document
.querySelectorAll('.nav__item a[href^="#"]')
.forEach(trigger => {
trigger.onclick = function(e) {
e.preventDefault();
let hash = this.getAttribute('href');
let target = document.querySelector(hash);
let headerOffset = 100;
let elementPosition = target.offsetTop;
let offsetPosition = elementPosition - headerOffset;
window.scrollTo({
top: offsetPosition,
behavior: "smooth"
});
};
});
Note
Please note there is also a new CSS property available to do the same trick, however you won't be able to offset it properly. This will cause issue when you are using a fixed navbar. In that case, JS Solution will be better.
About the author
Freelance Web & UX Designer from Incredible India. I design and develop creative websites, landing pages and applications for startups and e
Comments
Join the discussionBut we have a CSS property for smooth-scroll, right?? Why not use it??
Trust me I tried that as well.. But in some cases you will feel its not flexible. So this will come in handy.
Bookmarked, thanks for sharing.


