Smooth scroll without the use of jQuery
Ready for smooth scrolling fun? Use the native scrollIntoView
method:
That's neat right? Want to apply this globally to all hash-links? Here you go:
This turns jumpy anchor jumps into sweet, sweet smooth transitions.
Breakdown: An Ode to Smooth Scroll
Closer Look at scrollIntoView
The scrollIntoView
method offers an options object for fine tuning:
Custom Scroll Magic with window.scrollTo
Need complete control? Here's your wand: window.scrollTo
. Witness the magic:
This marvel lets you smooth scroll to the pinnacle of the document, easing as it ascends.
Dealing with the Bumps (Edge Cases)
While scroll-behavior: smooth
is now part of the cool kids club most browsers are in, always prepare for unexpected guests:
- User-led April fools: Users might spin the wheel or touch while the smooth scroll is having its moment. Monitor
wheel
andtouchmove
events to tackle this. - Dynamic Content Tricksters: The DOM could play tricks by changing the target position due to image loads or style changes. Be ready, stay sharp!
CSS for Better Scroll Behavior
The CSS Way to Smooth Scroll
Ever hear of HTML and CSS ruling the world? Here's scroll-behavior
featuring as a CSS property:
This little trick lets you enjoy smooth scrolling for all anchor tags and programmatic scrolls.
Scroll Enhancement, CSS Style
scroll-behavior
is what one might call progressive enhancement. Even if your browser thinks scroll-behavior
is too cool for it, scrolling still works as expected, albeit without the smoothness.
Pro-tips for Smooth Scrolling
Performance Optimization
To ensure your animation doesn't transform into slow-motion, use window.requestAnimationFrame
for an optimized, battery-friendly experience.
Catering to All Browsers
Even though we love living on the edge, ponder about using a polyfill for older, classical browsers. The Smoothscroll Polyfill addressed in the links below can come to your rescue.
Accessibility is Key
While we strive to make scrolling a fun experience, accessibility should remain at the forefront. Craft your smooth scroll considering keyboard-only users and those who depend on assistive technologies.
Was this article helpful?