JAVASCRIPT
Smoothly Scroll to Any DOM Element
Implement smooth scrolling to a specific HTML element using JavaScript's `scrollIntoView` method, enhancing navigation experience and user interface flow.
const targetElement = document.getElementById('section-id');
if (targetElement) {
targetElement.scrollIntoView({
behavior: 'smooth', // Smooth scroll animation
block: 'start' // Align the top of the element with the top of the viewport
});
// To scroll instantly:
// targetElement.scrollIntoView();
// Other useful options:
// block: 'center', 'end', 'nearest'
// inline: 'start', 'center', 'end', 'nearest'
}
/* Example HTML for context:
<div style="height: 1000px;">Scroll down</div>
<h2 id="section-id">Target Section</h2>
<div style="height: 1000px;">More content</div>
<button onclick="document.getElementById('section-id').scrollIntoView({ behavior: 'smooth' });">Scroll to Target</button>
*/
How it works: The `scrollIntoView()` method scrolls the element's parent container to make the element visible. By passing an options object, you can customize the scrolling behavior. Setting `behavior: 'smooth'` creates a gentle animation, while `block: 'start'` ensures the element's top edge aligns with the viewport's top. This is commonly used for 'scroll to top' buttons, internal anchor links, or guiding users to specific content on a page.