Smooth the scroll position with JS
Posted on February 8, 2019 in
2 min read
I've already written about the CSS gem scroll-behavior
, a property that allows animating the scroll position change of any HTML element with scroll capability.
In the previous tutorial, I've shown how it can be used together with anchor links, without relying on javascript at all.
This time I needed to achieve a particular micro-interaction in my side-project toy, Presenta, as briefly shown here:
The sidebar allows to select a specific item (the thumb) and the scroll position needs to be changed in order to keep a precise horizontal alignment between the thumb and the editor panel.
An immediate change would not be very user-friendly or even worse it would be highly annoying.
Scroll-Behavior to the rescue
Here the amazingness of CSS. With just one line of it, any scroll position changes will be nicely animated.
It's jus a matter of modifing the scrollTop
property of the HTML element to make the magic, such as:
document.querySelector('.mydiv').scrollTop = 100
If you have Chrome or Firefox you should see the animation here:
See the Pen Scroll-position-basic by Fabio Franchino (@abusedmedia) on CodePen.
Here a little Vue.js app (you know that I'm a fan of Vue.js?) that shows the meat (click the red thumbs 1):
See the Pen smooth scrolling to position by Fabio Franchino (@abusedmedia) on CodePen.
Have a nice day!