JAVASCRIPT

Smooth Scroll to an Element or Position

Implement smooth scrolling to any HTML element or specific vertical position on a webpage using the native `scrollIntoView` or `scrollTo` methods with behavior options.

function smoothScrollTo(target, offset = 0) {
  if (typeof target === 'string') {
    // Scroll to an element by ID
    const element = document.getElementById(target);
    if (element) {
      const y = element.getBoundingClientRect().top + window.pageYOffset + offset;
      window.scrollTo({ top: y, behavior: 'smooth' });
    } else {
      console.error(`Element with ID '${target}' not found.`);
    }
  } else if (typeof target === 'number') {
    // Scroll to a specific Y position
    window.scrollTo({ top: target + offset, behavior: 'smooth' });
  } else if (target instanceof HTMLElement) {
    // Scroll to an HTMLElement
    const y = target.getBoundingClientRect().top + window.pageYOffset + offset;
    window.scrollTo({ top: y, behavior: 'smooth' });
  } else {
    console.error('Invalid target for smoothScrollTo. Must be an ID string, Y coordinate number, or HTMLElement.');
  }
}

// Example usage:
// <div id="section2" style="height: 1000px; background-color: lightgray;">Section 2</div>
// <button onclick="smoothScrollTo('section2')">Scroll to Section 2</button>
// <button onclick="smoothScrollTo(500)">Scroll to Y=500</button>
How it works: This snippet demonstrates how to achieve smooth scrolling to an element or a specific vertical position on a webpage. It utilizes the modern `window.scrollTo()` method with the `behavior: 'smooth'` option for fluid animation. It can accept an element's ID, a direct Y-coordinate, or an HTMLElement object, making it versatile for various scrolling needs like "back to top" buttons or navigation to specific sections. The optional `offset` parameter allows adjusting the scroll position relative to the target.

Need help integrating this into your project?

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

Hire DigitalCodeLabs