JAVASCRIPT
Smoothly Scrolling to a Specific Element in the Viewport
Implement smooth, animated scrolling to any target HTML element on your webpage, enhancing user experience for navigation or highlighting specific content programmatically.
function scrollToElement(elementId, behavior = 'smooth', block = 'start') {
const targetElement = document.getElementById(elementId);
if (!targetElement) {
console.error(`Element with ID '${elementId}' not found.`);
return;
}
targetElement.scrollIntoView({
behavior: behavior, // 'auto' (instant) or 'smooth'
block: block // 'start', 'center', 'end', or 'nearest'
});
}
// Example Usage:
// Assume a long page with:
// <div id="topSection" style="height: 500px; background: lightblue;">Top</div>
// <div style="height: 1000px; background: lightgray;">Scrollable Content</div>
// <div id="targetSection" style="height: 500px; background: lightgreen;">Target</div>
// <div style="height: 500px; background: lightpink;">Bottom</div>
// <button onclick="scrollToElement('targetSection', 'smooth', 'center')">Scroll to Target (Center Smooth)</button>
// <button onclick="scrollToElement('topSection', 'auto', 'start')">Scroll to Top (Instant)</button>
// For demonstration, let's simulate a scroll after a delay.
setTimeout(() => {
console.log('Scrolling to targetSection in 2 seconds...');
scrollToElement('targetSection', 'smooth', 'center');
}, 2000);
setTimeout(() => {
console.log('Scrolling back to topSection in 5 seconds...');
scrollToElement('topSection', 'smooth', 'start');
}, 5000);
How it works: This snippet allows you to programmatically scroll to any element on a webpage. The `scrollIntoView()` method on an element provides native browser scrolling capabilities. By default, it uses `behavior: 'smooth'` for an animated scroll and `block: 'start'` to align the element's top with the viewport's top. You can customize `behavior` to 'auto' for an instant jump and `block` to 'center', 'end', or 'nearest' to control the alignment within the viewport.