JAVASCRIPT

Smoothly Scroll to Any Target Element

Implement smooth programmatic scrolling to bring a specific DOM element into the viewport, significantly enhancing user experience for navigation and focus changes on a webpage.

/**
 * Smoothly scrolls the viewport to bring a target DOM element into view.
 * @param {HTMLElement} targetElement The element to scroll to.
 * @param {'start'|'center'|'end'|'nearest'} [block='start'] Defines vertical alignment.
 * @param {'start'|'center'|'end'|'nearest'} [inline='nearest'] Defines horizontal alignment.
 */
function scrollToElementSmoothly(targetElement, block = 'start', inline = 'nearest') {
  if (!targetElement || !(targetElement instanceof HTMLElement)) {
    console.error('Invalid target element provided to scrollToElementSmoothly.');
    return;
  }
  targetElement.scrollIntoView({
    behavior: 'smooth',
    block: block,
    inline: inline
  });
}

// Example Usage:
// Assuming a long page with <section id="aboutUs">...</section>
// const aboutUsSection = document.getElementById('aboutUs');
// scrollToElementSmoothly(aboutUsSection); // Scrolls to the top of 'aboutUs' with smooth animation
// scrollToElementSmoothly(aboutUsSection, 'center'); // Scrolls to 'aboutUs' centered vertically
How it works: This snippet provides a function to smoothly scroll the browser viewport to a specified DOM element. It leverages the `Element.scrollIntoView()` method, which has options for controlling the scrolling behavior. By setting `behavior: 'smooth'`, the scroll animation is made gradual and user-friendly. The `block` and `inline` options allow for precise control over the vertical and horizontal alignment of the target element within the viewport, respectively.

Need help integrating this into your project?

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

Hire DigitalCodeLabs