JAVASCRIPT

Programmatically Scrolling an Element into View with Smooth Behavior

Guide users to specific sections of a page by programmatically scrolling any DOM element into the viewport, utilizing smooth scroll behavior for better UX.

// HTML Example:
// <div style="height: 1500px;">Scroll down to see element</div>
// <button id="scrollToTargetBtn">Scroll to Target</button>
// <div id="targetElement" style="height: 200px; background-color: lightblue; margin-top: 1000px;">I am the target element!</div>

const scrollToTargetBtn = document.getElementById('scrollToTargetBtn');
const targetElement = document.getElementById('targetElement');

scrollToTargetBtn.addEventListener('click', () => {
    // Scroll the target element into view
    targetElement.scrollIntoView({
        behavior: 'smooth', // Makes the scroll animation smooth
        block: 'start',     // Aligns the element's top to the viewport's top
        inline: 'nearest'   // Aligns the element's left/right to the nearest edge
    });
    console.log('Scrolled to target element.');
});

// Example with different options
const anotherElement = document.createElement('div');
anotherElement.id = 'anotherElement';
anotherElement.style.cssText = 'height: 300px; background-color: lightgreen; margin-top: 500px;';
anotherElement.textContent = 'Another element to scroll to (end)';
document.body.appendChild(anotherElement);

setTimeout(() => {
    // Scroll to another element, aligning its bottom to the viewport's bottom
    anotherElement.scrollIntoView({
        behavior: 'smooth',
        block: 'end'
    });
    console.log('Scrolled to another element (block: end).');
}, 2000); // Scroll after 2 seconds
How it works: The `Element.scrollIntoView()` method provides a powerful way to programmatically scroll an element into the visible area of the browser window. By passing an options object, you can control the scrolling behavior. Setting `behavior: 'smooth'` creates a fluid animation, while `block` and `inline` properties determine the vertical and horizontal alignment of the element within the viewport. This is highly useful for navigation, highlighting content, or bringing dynamically loaded elements 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