JAVASCRIPT

Smooth Scroll to Any DOM Element

Guide users to specific sections of your web page with a smooth scrolling effect using `scrollIntoView({ behavior: 'smooth' })`, enhancing navigation.

function smoothScrollToElement(elementId) {
    const element = document.getElementById(elementId);
    if (!element) {
        console.error(`Element with ID '${elementId}' not found.`);
        return;
    }

    element.scrollIntoView({
        behavior: 'smooth', // Makes the scroll animated
        block: 'start'      // Aligns the top of the element to the top of the viewport
        // You can also use 'center', 'end', or 'nearest' for 'block'
        // and 'start', 'center', 'end', or 'nearest' for 'inline'
    });
    console.log(`Smoothly scrolled to element with ID '${elementId}'.`);
}

// Example Usage:
// Assume <div id="section3" style="height: 1000px; background: lightblue;">Content</div>
// And a button to trigger it: <button onclick="smoothScrollToElement('section3')">Go to Section 3</button>
// smoothScrollToElement('section3');
How it works: This snippet provides a utility function to smoothly scroll the user's viewport to a specific DOM element. It uses the `scrollIntoView()` method available on all HTML elements. By setting `behavior: 'smooth'`, the browser animates the scroll, providing a better user experience than an instant jump. The `block: 'start'` option ensures the top of the target element aligns with the top of the visible area of the scrollable ancestor.

Need help integrating this into your project?

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

Hire DigitalCodeLabs