Back to Snippets
CODE
Smooth Scroll to Element
Description
Smoothly scrolls to a DOM element with configurable offset and behavior
Code
/**
* Smooth scroll to DOM element
* @param element Target element or selector
* @param offset Scroll offset in pixels
* @param behavior Scroll behavior ('auto' or 'smooth')
*/
function scrollToElement(
element: HTMLElement | string,
offset = 0,
behavior: ScrollBehavior = 'smooth'
): void {
const target = typeof element === 'string'
? document.querySelector(element)
: element;
if (!target) return;
const targetPosition = target.getBoundingClientRect().top + window.pageYOffset - offset;
window.scrollTo({
top: targetPosition,
behavior
});
}
// Usage Example
scrollToElement('#section-about', 20); // Scroll to #section-about with 20px offset
scrollToElement(document.getElementById('contact'), 0, 'auto'); // Instant scrollUsage
Perfect for navigation menus, back-to-top buttons, or smooth scrolling between page sections