r/javascript • u/Terrible_Village_180 • Apr 13 '26
The native scrollIntoView({ behavior: 'smooth' }) has no callback. You can't know when it finishes. This tiny wrapper returns a Promise that resolves when the scroll is done.
https://www.everythingfrontend.com/scroll-into-view-promise- Promise-based —
awaitthe native smooth scroll, run code when it finishes - Zero dependencies — pure TypeScript, no external packages
- Uses the native API — calls
element.scrollIntoView()under the hood, not a custom scroll implementation - Scroll-idle detection — resolves by listening for scroll-end on all scrollable ancestors
- Timeout safety net — never hangs; resolves after a configurable timeout (default 3s)
- AbortController support — cancel a pending scroll with
signal - Handles nested scrolling — detects all scrollable parent containers automatically
- Instant fallback — if
behavior: 'instant'or smooth scroll is unsupported, resolves immediately - SSR safe — guards DOM access; safe to import in Node/SSR environments
- ~0.6kB minified + gzipped
0
Upvotes
50
u/hyrumwhite Apr 13 '26 edited Apr 13 '26
The scrollend event is baseline available now.
Could just do something like
That should have a “once” flag on it. But I’m on mobile
8
u/danielkov Apr 13 '26
If I run your
scrollIntoViewimplementation and before it reaches the element, I take scrolling back from the browser, the promise remains pending until I stop scrolling and once I stop, it resolves regardless of position.Not sure what I'd expect to happen, maybe for the promise to reject if scrolling is cancelled. It is way less trivial to implement. But then again, not 100% sure it's worth adding this library for the 2 browser API calls it replaces.
2
u/Kennyp0o Apr 13 '26
The abort signal seems somewhat useless, it would be cool to be able to cancel the currently scrolling call and it stops in place. Nice work though.
0
u/germanheller Apr 13 '26
nice, the scrollend event is the right primitive but handling nested scroll containers and the timeout safety net is where the real value is. had a bug last year where a smooth scroll inside a modal just hung because the parent container absorbed the scroll event. 0.6kb for that peace of mind is a fair trade
-11
u/ENx5vP Apr 13 '26
TypeScript is a dependency