JAVASCRIPT
Implement Smooth Scroll to Any DOM Element
Guide users to specific sections of your page with a smooth scrolling effect using JavaScript's `scrollIntoView` method, enhancing user experience and navigation.
function smoothScrollToElement(targetElementId, offset = 0) {
const targetElement = document.getElementById(targetElementId);
if (!targetElement) {
console.error('Target element not found:', targetElementId);
return;
}
// For modern browsers: use scrollIntoView with 'smooth' behavior
if (typeof targetElement.scrollIntoView === 'function') {
// Calculate position considering offset
const elementRect = targetElement.getBoundingClientRect();
const absoluteElementTop = elementRect.top + window.pageYOffset;
const targetScrollPosition = absoluteElementTop - offset;
window.scrollTo({
top: targetScrollPosition,
behavior: 'smooth'
});
console.log(`Smooth scrolled to #${targetElementId} with offset ${offset}`);
} else {
// Fallback for older browsers: direct jump
targetElement.scrollIntoView(true);
console.warn(`Browser does not support smooth scrolling. Jumped to #${targetElementId}`);
}
}
// Example Usage:
// HTML:
// <a href="#section2" onclick="event.preventDefault(); smoothScrollToElement('section2', 20);">Go to Section 2</a>
// <div style="height: 800px; background-color: lightblue;">Section 1</div>
// <div id="section2" style="height: 600px; background-color: lightgreen; padding-top: 50px;">
// <h2>Section 2 Content</h2>
// <p>This is the content of section 2.</p>
// </div>
// <div style="height: 1000px; background-color: lightcoral;">Section 3</div>
// smoothScrollToElement('section2'); // Scrolls directly to section 2
// smoothScrollToElement('section2', 50); // Scrolls to section 2 with 50px offset from top
How it works: This snippet provides a reliable way to smoothly scroll the user's viewport to a specific DOM element. It leverages the modern `window.scrollTo()` method with the `behavior: 'smooth'` option, which provides native, hardware-accelerated smooth scrolling. An optional `offset` parameter allows you to adjust the final scroll position, which is useful for fixed headers or other UI elements that might obscure the top of the target element. For older browsers that don't support `behavior: 'smooth'`, it falls back to an instant jump using `scrollIntoView(true)`.