JAVASCRIPT

Smooth Scroll to a Specific DOM Element

Create a smooth scrolling effect to navigate to any target element on the page, enhancing user experience for navigation links or 'scroll to top' buttons.

document.addEventListener('DOMContentLoaded', () => {
  const smoothScrollLinks = document.querySelectorAll('a[href^="#"]');

  smoothScrollLinks.forEach(link => {
    link.addEventListener('click', (event) => {
      event.preventDefault(); // Prevent default jump behavior
      const targetId = link.getAttribute('href');
      const targetElement = document.querySelector(targetId);

      if (targetElement) {
        targetElement.scrollIntoView({
          behavior: 'smooth',
          block: 'start' // Align the top of the element with the top of the viewport
        });
        // Optional: Update URL hash without jumping
        history.pushState(null, null, targetId);
      }
    });
  });
});
How it works: This snippet enables smooth scrolling to anchor links (`href^="#"`). When a user clicks such a link, the default jump behavior is prevented. Instead, JavaScript finds the target element using its ID and then uses `scrollIntoView({ behavior: 'smooth' })` to smoothly animate the scroll to that element. This significantly improves the user experience for in-page navigation.

Need help integrating this into your project?

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

Hire DigitalCodeLabs