JAVASCRIPT
Smooth Scroll to Element with Custom Offset
Implement smooth scrolling to any target element on the page, optionally adjusting the scroll position with a custom offset to account for fixed headers or other UI elements.
const smoothScrollTo = (targetSelector, offset = 0) => {
const targetElement = document.querySelector(targetSelector);
if (targetElement) {
const elementPosition = targetElement.getBoundingClientRect().top + window.pageYOffset;
const offsetPosition = elementPosition - offset;
window.scrollTo({
top: offsetPosition,
behavior: "smooth"
});
console.log(`Smooth scrolled to '${targetSelector}' with offset ${offset}.`);
} else {
console.error(`Element with selector '${targetSelector}' not found.`);
}
};
// Example Usage:
// HTML: <div style="height: 1000px;">Content</div><h2 id="section2">Section 2</h2><div style="height: 1000px;">More Content</div>
// <button onclick="smoothScrollTo('#section2', 60)">Go to Section 2 (Offset 60px)</button>
How it works: This function provides a user-friendly way to scroll the viewport smoothly to a specific element on the page. It takes a CSS selector for the target element and an optional `offset` value. The `getBoundingClientRect().top` combined with `window.pageYOffset` calculates the element's absolute position from the top of the document. The `offset` is subtracted to adjust the final scroll position, which is particularly useful for preventing content from being obscured by fixed headers. `window.scrollTo` with `behavior: "smooth"` handles the animation.