JAVASCRIPT
Smoothly Scroll to Any Element
Learn how to smoothly scroll the user's view to any target element on a web page using JavaScript's `scrollIntoView` method with custom behavior for enhanced UX.
document.getElementById('myTargetElement').scrollIntoView({
behavior: 'smooth', // Makes the scroll animation smooth
block: 'start', // Aligns the element to the top of the viewport
inline: 'nearest' // Keeps the element fully visible horizontally
});
// Example usage with a button click
document.getElementById('scrollToDivButton').addEventListener('click', () => {
const target = document.getElementById('contentSection');
if (target) {
target.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
});
How it works: This snippet demonstrates how to programmatically scroll the browser window to a specific DOM element using the `scrollIntoView()` method. The `behavior: 'smooth'` option provides a visually pleasing animated scroll, while `block: 'start'` ensures the element's top edge aligns with the viewport's top. This is essential for navigation, 'back to top' buttons, or highlighting specific content.