DEV Community

Surjith S M
Surjith S M

Posted on

[Solved] 2020: Pure Vanilla Javascript Smooth Scroll to Element on 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"
            });
        };
    });

Top comments (5)

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
 
arvindrk profile image
Arvind Ram Singh Kishore

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'

Collapse
 
Sloan, the sloth mascot
Comment deleted
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.