JAVASCRIPT

Smoothly Scroll an Element into View

Learn how to programmatically scroll to any DOM element on your page, with an option for smooth scrolling behavior, enhancing user experience.

function scrollElementIntoView(elementId, smooth = true) {
    const element = document.getElementById(elementId);
    if (!element) {
        console.error('Element not found:', elementId);
        return;
    }

    element.scrollIntoView({
        behavior: smooth ? 'smooth' : 'auto',
        block: 'start', // Align the top of the element with the top of the viewport
        inline: 'nearest' // Only scroll horizontally if necessary
    });
}

// Example Usage:
// Assuming various elements exist on the page, e.g.,
// <div id="section-top" style="height: 100vh;">Top Section</div>
// <div id="section-middle" style="height: 100vh;">Middle Section</div>
// <div id="section-bottom" style="height: 100vh;">Bottom Section</div>

// Scroll smoothly to an element
// setTimeout(() => scrollElementIntoView('section-bottom'), 1000);

// Scroll instantly to an element
// setTimeout(() => scrollElementIntoView('section-top', false), 3000);

// For demonstration, let's add a button to trigger it
// <button onclick="scrollElementIntoView('section-bottom')">Go to Bottom</button>
// <button onclick="scrollElementIntoView('section-top', false)">Go to Top (Instant)</button>
How it works: This function allows you to programmatically scroll any specified DOM element into the user's viewport. It utilizes the `element.scrollIntoView()` method, which accepts an options object. The `behavior` option controls the animation (`'smooth'` for a gentle scroll, `'auto'` for an instant jump). `block` and `inline` define the vertical and horizontal alignment preferences within the viewport, respectively. This is highly useful for navigation, 'scroll to top' buttons, or bringing dynamically loaded content into focus.

Need help integrating this into your project?

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

Hire DigitalCodeLabs