JAVASCRIPT
Smoothly Scroll to a Target Element on the Page
Implement smooth scrolling to any element on your web page with JavaScript, enhancing user experience for navigation and focusing on specific content sections.
function scrollToElement(elementId) {
const targetElement = document.getElementById(elementId);
if (targetElement) {
targetElement.scrollIntoView({
behavior: 'smooth', // Makes the scroll animation smooth
block: 'start' // Aligns the top of the element to the top of the viewport
// inline: 'nearest' // Optional: aligns element to nearest side horizontally
});
} else {
console.warn(`Element with ID '${elementId}' not found.`);
}
}
// Usage example:
// Assuming you have an element with id='section2'
// <div style="height: 1000px;">Scrollable content</div>
// <h2 id="section2">Section 2</h2>
// <div style="height: 1000px;">More scrollable content</div>
// To scroll to 'section2' when a button is clicked:
// <button onclick="scrollToElement('section2')">Go to Section 2</button>
// Or call it directly:
// scrollToElement('section2');
How it works: This snippet provides a function to smoothly scroll the browser's viewport to a specific element on the page. It takes an element's ID, retrieves the element using `document.getElementById()`, and then calls `element.scrollIntoView()`. The `behavior: 'smooth'` option creates a gradual, animated scroll, improving the user experience compared to an instant jump. The `block: 'start'` option ensures that the top edge of the target element is aligned with the top edge of the viewport. This is a simple yet effective way to implement in-page navigation or bring important content into view.