JavaScript

Scroll to Element Smoothly

by @admin
10h ago
Apr 28, 2026
Public
Scrolls the page to a target element with an optional pixel offset (useful when a fixed header is present). Uses the native scrollIntoView with smooth behaviour when supported, and falls back to a manual scrollTo with a configurable offset. Pass a CSS selector string or an Element reference.
JavaScript
function scrollTo(target, offsetPx = 0) {
  const el = typeof target === 'string' ? document.querySelector(target) : target;
  if (!el) return;
  const top = el.getBoundingClientRect().top + window.scrollY - offsetPx;
  window.scrollTo({ top, behavior: 'smooth' });
}

// Usage — scroll to section, accounting for a 64px fixed nav
scrollTo('#contact', 64);

// Or smooth-scroll all anchor links
document.querySelectorAll('a[href^="#"]').forEach((a) => {
  a.addEventListener('click', (e) => {
    e.preventDefault();
    scrollTo(a.getAttribute('href'), 64);
  });
});
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.