JAVASCRIPT
Smoothly Scroll to a Specific DOM Element
Implement smooth scrolling to any target element on your web page using JavaScript's scrollIntoView() method, enhancing user navigation.
function scrollToElement(elementId, behavior = 'smooth') {
const targetElement = document.getElementById(elementId);
if (targetElement) {
targetElement.scrollIntoView({
behavior: behavior, // 'auto' or 'smooth'
block: 'start' // 'start', 'center', 'end', or 'nearest'
});
} else {
console.warn(`Element with ID '${elementId}' not found.`);
}
}
// Example HTML:
// <div style="height: 1000px;">Scroll down</div>
// <button onclick="scrollToElement('targetSection')">Go to Target</button>
// <div id="targetSection" style="height: 500px; background-color: lightblue;">This is the target section</div>
// <div style="height: 1000px;">More content</div>
// Example Usage:
// Call this from an event listener or directly:
// scrollToElement('targetSection');
// scrollToElement('anotherSection', 'auto'); // Instant scroll
How it works: This snippet provides a utility function to smoothly scroll the viewport to a specific DOM element identified by its ID. It leverages the element.scrollIntoView() method, which is a modern and declarative way to achieve scrolling without complex calculations. The behavior: 'smooth' option ensures a visually pleasing animated scroll, while block: 'start' positions the top of the element at the top of the viewport.