Skip to main content

How to Create a To Top Button With CSS Animated Smooth Scrolling

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.
Meme of the great Gatsby (Leonardo DiCaprio) saying thank you

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 = '#';
});

End

I know this is all simple stuff, but I hope some people will find it useful.

Comments

cusG_relatedPost_html

Popular posts from this blog

How to Add Next & Previous Post Navigation Buttons to Blogger

Street Fighter: Chun-Li Outtakes - Lilan Bowden

Japanizing