Skip to content

Instantly share code, notes, and snippets.

@ricardozea
Last active January 4, 2023 02:13
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save ricardozea/ec045dfb5bdd1df6f22015ee25d649a8 to your computer and use it in GitHub Desktop.
Save ricardozea/ec045dfb5bdd1df6f22015ee25d649a8 to your computer and use it in GitHub Desktop.
Smooth scroll to top of page (Improved!)
window.scrollTo({top: 0, behavior: "smooth"});
<button onclick='window.scrollTo({top: 0, behavior: "smooth"});'>Back to Top ↑</button>

Smooth scroll to top of page (Improved!)

If you need a plain JavaScript function to add a smooth scrolling back to the top of the page, you can use this script:

window.scrollTo({top: 0, behavior: "smooth"});

How? 👉 Just add this script to a <button> element in the onclick: attribute, like this (and place it at the bottom of your page):

<button onclick='window.scrollTo({top: 0, behavior: "smooth"});'>Back to Top ↑</button>

CodePen demo here: (https://codepen.io/ricardozea/pen/NWpgyjL) by Ricardo Zea on CodePen.

License.

@lanuma
Copy link

lanuma commented Jul 16, 2021

Thank you for your update.

this script simple and working perfect

@ricardozea
Copy link
Author

Thank you for your update.

this script simple and working perfect

No problem, glad you found the script helpful 👍

@ennuirose
Copy link

How do I add CSS to the button, to give it a more dynamic, round shape?

@ricardozea
Copy link
Author

You can use the border-radius property in the button class. Check out the demo in CodePen, you can play with the CSS there without affecting the final output. You can also fork the demo and play with it and save the changes for yourself.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment