JAVASCRIPT

Smooth Scroll to Any Element on the Page

Implement smooth, animated scrolling to a specific HTML element using modern JavaScript APIs, enhancing user experience for navigation menus or "scroll to top" features.

function smoothScrollToElement(targetElementId, offset = 0) {
    const targetElement = document.getElementById(targetElementId);
    if (!targetElement) {
        console.error(`Target element with ID '${targetElementId}' not found.`);
        return;
    }

    // Get the target element's position relative to the viewport
    const elementPosition = targetElement.getBoundingClientRect().top;
    // Calculate the distance to scroll
    const distance = elementPosition - offset;

    window.scrollBy({
        top: distance,
        behavior: 'smooth'
    });

    // Alternative modern approach (simpler but doesn't allow offset as easily for just 'behavior: smooth')
    // targetElement.scrollIntoView({
    //     behavior: 'smooth',
    //     block: 'start' // or 'center', 'end', 'nearest'
    // });

    console.log(`Attempting to smooth scroll to element: ${targetElementId} with offset: ${offset}`);
}

// Example Usage:
// HTML:
/*
<nav>
    <a href="#section1" id="scrollToSection1">Go to Section 1</a>
    <a href="#section2" id="scrollToSection2">Go to Section 2</a>
</nav>
<div style="height: 800px; background-color: #f0f0f0;"></div>
<section id="section1" style="height: 500px; background-color: lightblue;">
    <h2>Section 1</h2>
</section>
<div style="height: 800px; background-color: #f0f0f0;"></div>
<section id="section2" style="height: 700px; background-color: lightgreen;">
    <h2>Section 2</h2>
</section>
*/

document.addEventListener('DOMContentLoaded', () => {
    const scrollBtn1 = document.getElementById('scrollToSection1');
    const scrollBtn2 = document.getElementById('scrollToSection2');

    scrollBtn1?.addEventListener('click', (e) => {
        e.preventDefault(); // Prevent default anchor jump
        smoothScrollToElement('section1', 60); // Offset by 60px for a fixed header, for example
    });

    scrollBtn2?.addEventListener('click', (e) => {
        e.preventDefault();
        smoothScrollToElement('section2'); // No offset
    });
});
How it works: This snippet provides a function to smoothly scroll the user's view to a specific HTML element identified by its ID. It calculates the required scroll distance and uses `window.scrollBy()` with the `behavior: 'smooth'` option for an animated scroll. An optional `offset` parameter allows adjusting the final scroll position, which is useful for fixed headers or navigation bars. This modern JavaScript API provides a much cleaner solution than manually animating scroll positions for enhanced 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