Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save juliaogris/288db65d77fdab8efc3187ac750d5193 to your computer and use it in GitHub Desktop.
Save juliaogris/288db65d77fdab8efc3187ac750d5193 to your computer and use it in GitHub Desktop.
[JavaScript] Smooth scroll to top of page
<body id="top">
<a href="#top" onclick="scrollToTop();return false">Back to Top &uarr;</a>
var timeOut;
function scrollToTop() {
if (document.body.scrollTop!=0 || document.documentElement.scrollTop!=0){
window.scrollBy(0,-50);
timeOut=setTimeout('scrollToTop()',10);
}
else clearTimeout(timeOut);
}

Smooth scroll to top of page

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
  2. Add the onclick function to the link
  3. Include the JavaScript function in your HTML file, preferrably at the bottom 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.

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

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