JAVASCRIPT

Smoothly Scrolling to a Specific DOM Element

Implement smooth, animated scrolling to any target DOM element on your page using native JavaScript, enhancing user navigation and experience.

function smoothScrollTo(selector, offset = 0) {
  const targetElement = document.querySelector(selector);
  if (targetElement) {
    const elementPosition = targetElement.getBoundingClientRect().top + window.pageYOffset;
    const offsetPosition = elementPosition - offset;

    window.scrollTo({
      top: offsetPosition,
      behavior: 'smooth'
    });
  } else {
    console.warn(`Element with selector "${selector}" not found.`);
  }
}

// Example Usage:
// Assume <h2 id="section-2">Section Two</h2>
// Call this when a link is clicked:
// document.getElementById('myNavLink').addEventListener('click', (e) => {
//   e.preventDefault();
//   smoothScrollTo('#section-2', 70); // Scroll to #section-2, accounting for a fixed header of 70px
// });
How it works: This snippet provides a utility function for smoothly scrolling the viewport to a specific DOM element. It takes a CSS selector and an optional `offset` (useful for fixed headers) to calculate the target scroll position. Using `window.scrollTo` with `behavior: 'smooth'` enables native browser-level animated scrolling, offering a pleasant user experience without the need for external libraries. The `getBoundingClientRect().top` combined with `window.pageYOffset` accurately determines the element's absolute position on the page.

Need help integrating this into your project?

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

Hire DigitalCodeLabs