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