DEV Community

loading...

[Solved] 2020: Pure Vanilla Javascript Smooth Scroll to Element on anchor tag click #id

Surjith S M
Freelance Web & UX Designer from Incredible India. I design and develop creative websites, landing pages and application
・1 min read

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"
            });
        };
    });

Discussion (3)

Collapse
mattmischuk profile image
Matt Mischuk

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.

html { scroll-behavior: smooth; }
Enter fullscreen mode Exit fullscreen mode
Collapse
kazirezaurrahman profile image
Kazi-Rezaur-Rahman

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?"

Collapse
niccolomineo profile image
Niccolò Mineo • Edited

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.