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 (4)

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
niccolomineo profile image
Niccolรฒ Mineo • Edited on

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.

๐ŸŒš Browsing with dark mode makes you a better developer.

It's a scientific fact.