DEV Community

Cover image for Vanilla JavaScript Scroll to Top

Vanilla JavaScript Scroll to Top

Chris Bongers on June 13, 2020

Let's create a JavaScript powered scroll to top function. We will create a button that will sit at the right bottom of the page, and once we click ...
Collapse
 
easrng profile image
easrng • Edited

Easier method with no JS:
Add this right after the opening body tag:

<a name="top"></a>

For the scroll to top button use the code

<a href="#top" class="scroll-top">☝️</a>
Collapse
 
darival profile image
Darival • Edited

No need to make the target tag an anchor, a hidden div is enough
Also add:

html {
  scroll-behavior: smooth;
}

To make it smooth

Collapse
 
dailydevtips1 profile image
Chris Bongers

The smooth behaviour is a welcome addition, I've wrote an article about this method as well: daily-dev-tips.com/posts/plain-htm...

Collapse
 
mhm13dev profile image
Mubashir Hassan

A Codepen will help a lot!

Collapse
 
dailydevtips1 profile image
Chris Bongers

Hey Mubashir, In this article you will find a Codepen. daily-dev-tips.com/posts/plain-htm...

Thread Thread
 
mhm13dev profile image
Mubashir Hassan

Thank you for the post... It was helpful

Thread Thread
 
dailydevtips1 profile image
Chris Bongers

Thanks man, glad it helped! 🤟

Collapse
 
mzaini30 profile image
Zen

it's not work in hash spa mode (like site.com/#read/35)

Collapse
 
dailydevtips1 profile image
Chris Bongers

Hey Zen, I do indeed think the Hash needs to be in the end for the browser to understand

Collapse
 
dailydevtips1 profile image
Chris Bongers

Hey Easrng, I've wrote an article about this function as well today: daily-dev-tips.com/posts/plain-htm...

Collapse
 
dailydevtips1 profile image
Chris Bongers

Yes, aware of this, super solution as well.

I will do another article about this way. There are just so many ways of doing the same thing really :D