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"
});
};
});
Top comments (5)
Had trouble finding a solution that would work on a certain project that had a strange Babel config. This CSS only solution worked for me.
document
.querySelectorAll('.nav__item a[href^="#"]')
.forEach(trigger => {
trigger.onclick = function(e) {
e.preventDefault();
"Can you please explain what do you mean by 'trigger' in here?"
Trigger is the respective DOM Node that is being looped over using the forEach. Also, a onClick handler is being attached to each anchor tag using the same variable 'trigger'
Unfortunately, right now this solution does not provide access to heaven: compatibility with Safari. The only working solution that is simple, is also rather rubbish: jQuery.