JAVASCRIPT
Smooth Scroll to a Specific Element with JavaScript
Implement smooth scrolling to any target element on your webpage using the native `scrollIntoView()` method with a behavior option, enhancing user navigation and experience.
function scrollToElement(targetId) {
const targetElement = document.getElementById(targetId);
if (!targetElement) {
console.error(`Element with ID '${targetId}' not found.`);
return;
}
targetElement.scrollIntoView({
behavior: 'smooth',
block: 'start' // 'start', 'center', 'end', or 'nearest'
});
console.log(`Smooth scrolled to element #${targetId}.`);
}
// Example usage:
// In your HTML:
// <nav><a href="#section2" onclick="scrollToElement('section2'); return false;">Go to Section 2</a></nav>
// <div style="height: 800px; background: lightgray;">Section 1</div>
// <div id="section2" style="height: 800px; background: lightblue;">Section 2 Content</div>
// <div style="height: 800px; background: lightcoral;">Section 3</div>
How it works: The `scrollIntoView()` method is a native browser API that allows you to programmatically scroll an element into the visible area of the browser window. This snippet demonstrates how to use it with options to achieve a smooth scrolling effect. By setting `behavior: 'smooth'`, the browser animates the scroll, providing a better user experience than an instant jump. The `block` option controls the vertical alignment of the element within the viewport (e.g., 'start' aligns the top of the element with the top of the viewport).