← Back to all snippets
JAVASCRIPT

Programmatically Scroll to an Element with Smooth Behavior

Implement smooth scrolling to any target DOM element using JavaScript's `scrollIntoView` method. Enhance user experience by guiding visitors to specific content sections seamlessly.

/**
 * Scrolls the viewport to a specified DOM element with a smooth animation.
 * @param {HTMLElement} element - The target DOM element to scroll to.
 * @param {ScrollIntoViewOptions} options - Options for scrolling, e.g., { behavior: 'smooth', block: 'start' }.
 */
function scrollToElement(element, options = { behavior: 'smooth', block: 'start' }) {
  if (!(element instanceof HTMLElement)) {
    console.error('Invalid element provided. Must be an HTMLElement.');
    return;
  }
  element.scrollIntoView(options);
}

// Example Usage:
// Assuming you have an element with ID 'targetSection'
// const targetSection = document.getElementById('targetSection');
// if (targetSection) {
//   scrollToElement(targetSection); // Scrolls smoothly to the top of the element
//
//   // Or with custom options, e.g., scroll to the center
//   // scrollToElement(targetSection, { behavior: 'smooth', block: 'center', inline: 'nearest' });
// }
How it works: This snippet provides a reusable function to programmatically scroll the user's viewport to a specific DOM element. It leverages the `element.scrollIntoView()` method, which is a native browser API. By default, it uses `behavior: 'smooth'` for a visually pleasing animation, and `block: 'start'` to align the element to the top of the viewport. Custom options can be passed to control the scrolling behavior and alignment.

Need help integrating this into your project?

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

Hire DigitalCodeLabs