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.