JavaScript: Smooth scroll to an element with zero dependencies
Last updated: 5th August 2020Introduction
You can smooth scroll to an element with zero dependencies. You can achieve this programmatically in JavaScript, and you can also enable smooth scrolling from CSS. Browser support is good!
Using JavaScript
To do this programmatically through JavaScript, use this code:
el.scrollIntoView({
behavior: 'smooth'
})
There's actually two interesting things about that code above, yes you can smooth scroll, but secondly, turns out there's a built in method for scrolling an element into the viewport.
Using plain CSS
Depending on your use case, you might be able to avoid JavaScript entirely, and achieve this through CSS only:
html {
scroll-behavior: smooth;
}
This does not affect manual scrolling performed by the user, but it will impact for example, an internal link on a page such a back to top hyperlink:
<!--
This smooth scrolls to the top
thanks to scroll-behavior: smooth
-->
<a href="#top">Back to top</a>
Browser support
Browser support is pretty good, but there are some limitations with Safari:
Users who prefer reduced motion
Consider using the CSS media feature: prefers-reduced-motion
to toggle the 'smooth'
option since not everyone wants heavy animations/transitions on a website.
@media (prefers-reduced-motion) {
.animation {
animation-name: none;
}
}
As a reminder, prefers reduced motion does not mean no motion, so consider that point when altering your user experience for such users.
Here's the documentation for prefers-reduced-motion.
You can Emulate this CSS Media Feature from the Chrome DevTools Command Palette to make sure your media queries are working as expected:
- Use the shortcut Cmd + Shift + P
- Search for:
reduced-motion
- Hit enter
Conclusion
Hope you've learnt something new. JavaScript has lots of interesting features which aren't always obvious. If you want to look further, note that you can Automatically remove an event listener after it has executed.