JAVASCRIPT
Scrolling to a Specific Element with Smooth Animation
Implement smooth scrolling to any target HTML element on the page using JavaScript's `scrollIntoView` method, enhancing navigation and user experience.
// Assume you have several sections and a navigation link for one of them:
// <div style="height: 1000px; background-color: lightblue;">Scroll down to see target</div>
// <section id="target-section" style="height: 500px; background-color: lightgreen; border: 2px solid green;">
// <h2>Target Section</h2>
// <p>This is the section you want to scroll to.</p>
// </section>
// <div style="height: 1000px; background-color: lightcoral;">More content below</div>
// <button id="scroll-btn">Scroll to Target Section</button>
function scrollToElement(elementId) {
const targetElement = document.getElementById(elementId);
if (targetElement) {
targetElement.scrollIntoView({
behavior: 'smooth',
block: 'start' // Aligns the top of the element to the top of the scroll area
});
console.log(`Scrolled to element with ID: ${elementId}`);
} else {
console.warn(`Element with ID '${elementId}' not found.`);
}
}
// Example Usage:
document.getElementById('scroll-btn')?.addEventListener('click', () => {
scrollToElement('target-section');
});
How it works: This snippet illustrates how to programmatically scroll the user's view to a specific HTML element using the `scrollIntoView()` method. This method is called directly on the target DOM element. By setting the `behavior` option to `'smooth'`, the browser animates the scroll, providing a more pleasant user experience than an instant jump. The `block: 'start'` option ensures that the top edge of the target element aligns with the top of the scrollable area.