JAVASCRIPT

Implementing Smooth Scroll Navigation to Anchor Links

Create a seamless user experience by adding smooth scrolling behavior to anchor links, guiding users gently to specific sections within a web page.

function setupSmoothScroll(selector = 'a[href^="#"]') {
  document.querySelectorAll(selector).forEach(anchor => {
    anchor.addEventListener('click', function (e) {
      e.preventDefault(); // Prevent default jump behavior

      const targetId = this.getAttribute('href');
      const targetElement = document.querySelector(targetId);

      if (targetElement) {
        // Use smooth scroll behavior if supported, fallback to instant otherwise
        targetElement.scrollIntoView({
          behavior: 'smooth',
          block: 'start' // Align the top of the element with the top of the viewport
        });

        // Optionally update the URL hash without jumping
        // window.history.pushState(null, '', targetId);
      }
    });
  });
}

// Example Usage:
// <nav>
//   <a href="#section1">Go to Section 1</a>
//   <a href="#section2">Go to Section 2</a>
// </nav>
// <div id="section1" style="height: 500px; background-color: lightblue;">Section 1</div>
// <div id="section2" style="height: 500px; background-color: lightgreen;">Section 2</div>

// Call the function to enable smooth scrolling on all anchor links
// setupSmoothScroll();

// Or for specific links:
// setupSmoothScroll('.my-custom-links a');
How it works: This snippet enables smooth scrolling to anchor links on a page. Instead of the browser's default instant jump, it uses `scrollIntoView({ behavior: 'smooth' })` to animate the scroll to the target element. This improves user experience by providing a visual cue of navigation. It targets all links starting with `#` by default, but can be customized with a different CSS selector.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs