Skip to content

Instantly share code, notes, and snippets.

@ricardozea
Last active May 12, 2024 12:12
Show Gist options
  • Save ricardozea/abb9f98a19f6d04a0269 to your computer and use it in GitHub Desktop.
Save ricardozea/abb9f98a19f6d04a0269 to your computer and use it in GitHub Desktop.
Smooth scroll to top of page
<body id="top">
<a href="#top" onclick="scrollToTop();return false">Back to Top &uarr;</a>
function scrollToTop() {
var position =
document.body.scrollTop || document.documentElement.scrollTop;
if (position) {
window.scrollBy(0, -Math.max(1, Math.floor(position / 10)));
scrollAnimation = setTimeout("scrollToTop()", 30);
} else clearTimeout(scrollAnimation);
}

Visit the new improved script here! Smooth scroll to top of page (Improved!)


Smooth scroll to top of page (Legacy!)

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

  1. Add an id of "top" to the <body> tag. Like this: <body id="top">
  2. Add the onclick function to the link. Like this: <a href="#top" onclick="scrollToTop(); return false">Back to Top ↑</a>
  3. Then either:
  • Include the JavaScript function in your markup, preferrably at the bottom before the closing </body> tag if possible.
  • Or, create a JavaScript file, place the script in it and call that file from your HTML document (either from the </head> section, or before the closing </body> tag if possible.)

Since this script is not part of the UI it can load last and will not negatively affect the user experience or usability of the page.

CodePen demo here: https://codepen.io/ricardozea/pen/5f756e303d5adc25ca3876e6a81c9e57

Author: Marco Del Corno - http://thewebthought.blogspot.com/2012/06/javascript-smooth-scroll-to-top-of-page.html

Copy link

ghost commented Jul 17, 2015

Simple and clean. Exactly what I needed. Thank you.

@dariodepaolis
Copy link

Nice!

@LeoMouraIot
Copy link

Woww Exactly what I needed

@ZnOX
Copy link

ZnOX commented Jun 30, 2016

Cool!

@Thomas-Rudge
Copy link

Very succinct, thanks!

@dealloc
Copy link

dealloc commented Sep 19, 2016

Wouldn't it be more performant to use requestAnimationFrame for this kind of stuff?
I modified the sample to this

function scrollToTop() {
    if (document.body.scrollTop !== 0 || document.documentElement.scrollTop !== 0) {
        window.scrollBy(0, -50);
        requestAnimationFrame(scrollToTop);
    }
}

@superjose
Copy link

@dealloc: Yes! You are correct. It's more important since requestAnimationFrame offers the best performance

@fbparis
Copy link

fbparis commented Jan 11, 2018

To get a ease-out effect and keep it simple, I've done this:

	function scrollToTop() {
		var position = document.body.scrollTop || document.documentElement.scrollTop;
		if (position){
			window.scrollBy(0,-Math.max(10, Math.floor(position / 10)));
			scrollAnimation=setTimeout('scrollToTop()',10);
		}
		else clearTimeout(scrollAnimation);
	}		

@rfw
Copy link

rfw commented Mar 30, 2018

Nice! Cool! 很赞

@CoAmA
Copy link

CoAmA commented Aug 19, 2018

thanks for putting it here

@SeanCassiere
Copy link

Could anyone show me how I could add this code in with an Event Listener?

@christophernarciso
Copy link

Thank you for this snippet.

@ClaudiaPrez
Copy link

great. It work!

@ricardozea
Copy link
Author

Updated the Gist with a link to a demo in CodePen and used @fbparis' script with a few small variations to improve the ease-out effect.

Thanks everyone!

@dinizgb
Copy link

dinizgb commented Apr 30, 2020

@dealloc Great work.

@akmmp241
Copy link

akmmp241 commented Jun 2, 2020

good job and thank you

@uzair004
Copy link

uzair004 commented Aug 19, 2020

Could anyone show me how I could add this code in with an Event Listener?

it's already attached to that link but if you want to do it another way (event listener)

anchor.addEventListener('click', scrollToTop)

make sure anchor link is selected first using document.querySelector() or document.getElementById() if you have id for it

@LeoTheGreatGoat
Copy link

Is their a way to override the animation if you scroll?

@ricardozea
Copy link
Author

Is their a way to override the animation if you scroll?

There is no animation when scrolling. Would you mind elaborating?

@LeoTheGreatGoat
Copy link

LeoTheGreatGoat commented May 24, 2021 via email

@ricardozea
Copy link
Author

Don't scroll.

@LeoTheGreatGoat
Copy link

LeoTheGreatGoat commented May 24, 2021 via email

@ricardozea
Copy link
Author

Sr., I wish I could help you better but you need to provide more context to your question.

@LeoTheGreatGoat
Copy link

LeoTheGreatGoat commented May 24, 2021

When you click on the hyperlink it automatically scrolls to the top, because of the script you made. When I refer to "animation" it is the action that happens, THIS. My issue is that when you manually scroll with the scroll wheel, the animation still plays. I am asking if their is a way to make the animation stop when scrolling.

This is the most detailed way I can explain it.

@ricardozea
Copy link
Author

ricardozea commented May 24, 2021

I have good news and bad news.

The good news is that I now understand your question, thanks a lot for clarifying. The other good news is that I'm sure that what you're asking is doable.

The bad news is that I don't know how to accomplish that since I'm not a JavaScript developer so I have very little JS knowledge. Maybe someone here could help add that feature you mentioned.

Regards.

@LeoTheGreatGoat
Copy link

Thank you. I am sorry for the miscommunication.

@ricardozea
Copy link
Author

No problem at all Leo. In fact, I should be the one apologizing for not understanding your point off the bat in the first place, haha.

With that said, your question merits implementation, that's a HUGE UX win if you ask me. So I'm asking for help to see if we can get your suggestion/functionality added.

Stay tunned…

@ricardozea
Copy link
Author

Update 5/25/21

There's a new, improved version of this functionality! Check it out here: https://gist.github.com/ricardozea/ec045dfb5bdd1df6f22015ee25d649a8

--

The script in this Gist is no longer the recommended way to add smooth scrolling. I'm leaving this page available for reference only.

Thank you everyone!

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