In the old days, when we wanted the scrolling effect to be animated, we had to write custom JavaScript to animate the scroll position one frame at a time. I had a blast learning how animations worked and how to animate things in JavaScript. Now, thanks to advancements in CSS, my skills are increasingly becoming obsolete.
By default, the behaviour is
If we change it to
For our to top button, we want the whole page to scroll to the top and animated, so we will set the property on the
Introducing scroll-behavior
This new (new for me) CSS property sets the scroll behaviour for an element so that when the scroll position is changed, the browser will scroll to the new position using the specified behaviour.By default, the behaviour is
auto
, which means no animation, and the browser jumps the scroll position to the new position instantly.If we change it to
smooth
, then the scrolling becomes animated.For our to top button, we want the whole page to scroll to the top and animated, so we will set the property on the
html
element.Code Example
HTML
First, we want to create our button in HTML:<button id="to-top-btn">To Top</button>
CSS
Then we want to specify the animated scroll for the whole page in CSS:html{
scroll-behavior: smooth;
}
JavaScript
Finally, we change the scroll position of the page whenever the button is clicked:const BTN = document.getElementById('to-top-btn');
BTN.addEventListener('click', function(evt) {
window.location.hash = '#';
//for webkit
window.location.href = '#';
});
Comments
Post a Comment