[Solved] 2020: Pure Vanilla Javascript Smooth Scroll to Element on anchor tag click #id
Surjith S M
Posted on August 26, 2020
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"
});
};
});
💖 💪 🙅 🚩
Surjith S M
Posted on August 26, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
javascript [Solved] 2020: Pure Vanilla Javascript Smooth Scroll to Element on anchor tag click #id
August 26, 2020