Skip to main content
Back to the Top without Javascript

Back to the Top without Javascript

In my lifelong quest to minimize the code required to display my view of the world (aka this website) I today realised, that I can get rid of all the Javascript to display my “Back to top” button. Just look at this commit.

Up to now I had a button that was hidden by default and shown when the user scrolled down a certain amount of pixels. This was done with a bit of Javascript. I also had a bit of Javascript to scroll to the top of the page when the button was clicked.

It turns out this is not necessary. I can do all of this with CSS.

And it’s not even a lot of CSS.

The two pillars of this “trick” are position: sticky and margin-top: 105vh. Basically, what I am doing is positioning the back to top button just below the bottom of the page and then make it sticky, once it scrolls into the viewport. Of course, this whole procedure needs some positioning and floating or flexing, but that’s it.

My final SCSS snippet looks like this:

 1.btn-back-to-top {
 2
 3  @extend .btn;
 4  @extend .btn-dark;
 5
 6  @extend .d-flex;
 7  @extend .flex-row-reverse;
 8  @extend .justify-content-end;
 9
10  margin-top: 105vh;
11  position: sticky;
12  bottom: 1rem;
13  right: 1rem;
14  float: right;
15
16}

Most of this is just styling the button.

CSS has come a long way since back in the days when we used HTML tables to put layouts together.

Back to top
Back Forward