Home / Smooth Scrolling for Anchor Links
Duplicate Snippet

Embed Snippet on Your Site

Smooth Scrolling for Anchor Links

Enables smooth scrolling for all on-page links with #.

50+
Code Preview
js
document.addEventListener('click', function(e) {
    // Check if the clicked element is an anchor with href starting with '#'
    if (e.target.tagName === 'A' && e.target.getAttribute('href') && e.target.getAttribute('href').startsWith('#')) {
        e.preventDefault();
        const targetId = e.target.getAttribute('href').slice(1); // Remove the '#' from the href
        const targetElement = document.getElementById(targetId);
        
        if (targetElement) {
            targetElement.scrollIntoView({
                behavior: 'smooth'
            });
        }
    }
});

Comments

Add a Comment