JAVASCRIPT
Smoothly Scroll to a Specific Element on the Page
Learn how to programmatically scroll the browser window to bring a target HTML element into view with smooth animation and customizable positioning options.
const targetElement = document.getElementById('section-id');
// Attach to a button click or other event
document.getElementById('scrollToTargetButton').addEventListener('click', () => {
if (targetElement) {
targetElement.scrollIntoView({
behavior: 'smooth', // Makes the scroll animated
block: 'start', // Aligns the top of the element to the top of the viewport
inline: 'nearest' // Scrolls horizontally only if needed
});
} else {
console.error('Target element not found!');
}
});
// Example HTML for context (needs enough content to scroll):
// <button id="scrollToTargetButton">Go to Section</button>
// <div style="height: 1000px;">Scrollable content above...</div>
// <h2 id="section-id">Target Section</h2>
// <div style="height: 1000px;">Scrollable content below...</div>
How it works: This snippet shows how to programmatically scroll to a specific HTML element using `element.scrollIntoView()`. This method is highly useful for 'scroll to top' buttons, in-page navigation, or bringing important dynamic content into the user's view. The example demonstrates using options like `behavior: 'smooth'` for animated scrolling and `block: 'start'` to align the top of the target element with the top of the viewport, providing a user-friendly navigation experience.