JAVASCRIPT

Scroll an HTML Element into View Programmatically

Guide users to specific content by programmatically scrolling any HTML element into the visible part of the browser window using JavaScript's `scrollIntoView()` method.

function scrollToElement(elementId, behavior = 'smooth', block = 'start') {
    const element = document.getElementById(elementId);
    if (element) {
        element.scrollIntoView({
            behavior: behavior, // 'auto' or 'smooth'
            block: block,       // 'start', 'center', 'end', or 'nearest'
            inline: 'nearest'   // 'start', 'center', 'end', or 'nearest' (optional)
        });
        console.log(`Scrolled element with ID '${elementId}' into view.`);
    } else {
        console.warn(`Element with ID '${elementId}' not found.`);
    }
}

// Example Usage:
// Assuming there's a <div id="targetSection">...</div> far down the page
// scrollToElement('targetSection'); // Smooth scroll to the top of the section
// scrollToElement('anotherElement', 'auto', 'center'); // Instant scroll, element centered
How it works: This function provides a way to programmatically scroll an HTML element into the visible area of the browser window. It uses the `element.scrollIntoView()` method, which accepts an options object to customize the scrolling behavior (e.g., `'smooth'` for animation or `'auto'` for instant scroll) and the alignment of the element within the viewport (`block` and `inline`). This is useful for "scroll to top" buttons, "jump to section" links, or guiding user attention.

Need help integrating this into your project?

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

Hire DigitalCodeLabs