JAVASCRIPT

Smooth Scrolling an Element into View

Implement smooth, programmatic scrolling to bring any DOM element into the user's viewport, enhancing user experience for navigation or alerts.

function smoothScrollIntoView(elementId, behavior = 'smooth', block = 'start', inline = 'nearest') {
    const element = document.getElementById(elementId);
    if (!element) {
        console.error("Element not found with ID:", elementId);
        return;
    }

    element.scrollIntoView({
        behavior: behavior, // 'auto' or 'smooth'
        block: block,       // 'start', 'center', 'end', or 'nearest'
        inline: inline      // 'start', 'center', 'end', or 'nearest'
    });
}

// Example Usage:
// // Assume a long page with an element like <div id="targetSection" style="height: 500px; background: lightblue; margin-top: 1000px;">Target Section</div>
//
// // Scroll to the target section smoothly, aligning its top with the viewport top
// // smoothScrollIntoView('targetSection', 'smooth', 'start');
//
// // Scroll to the target section smoothly, centering it in the viewport
// // smoothScrollIntoView('targetSection', 'smooth', 'center');
//
// // Example with a button click
// // document.getElementById('scrollToTargetBtn').addEventListener('click', () => {
// //     smoothScrollIntoView('targetSection', 'smooth', 'center');
// // });
How it works: This snippet demonstrates how to programmatically scroll a specific DOM element into the visible part of the user's browser window using `element.scrollIntoView()`. It leverages the modern API to allow for smooth scrolling (`behavior: 'smooth'`) and precise control over the alignment of the element within the viewport (`block` and `inline` options), significantly improving user experience.

Need help integrating this into your project?

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

Hire DigitalCodeLabs