The WPFolks app is out on iPhone. Free, no ads. Download on the App Store
Skip to main content
Login Join
Snippet · JavaScript

Smooth Scroll to an Anchor

Shared by Hiral solanki · September 17, 2026

7 views
2 upvotes
Back to Snippets

Adds smooth scrolling behavior to internal anchor links and works well for one-page WordPress websites and navigation menus.

document.addEventListener('DOMContentLoaded', function () {
    document.querySelectorAll('a[href^="#"]').forEach(function (link) {
        link.addEventListener('click', function (event) {
            const targetId = link.getAttribute('href');

            if (!targetId || targetId === '#') {
                return;
            }

            const target = document.querySelector(targetId);

            if (!target) {
                return;
            }

            event.preventDefault();

            target.scrollIntoView({
                behavior: 'smooth',
                block: 'start'
            });
        });
    });
});
Know a different way to do this? Add your approach as a variation so folks can compare them side by side.
Submit a variation

0 comments