Smooth scroll to top of page
Visit the new improved script here! 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.
<body>
tag. Like this: <body id="top">
onclick
function to the link. Like this: <a href="#top" onclick="scrollToTop(); return false">Back to Top ↑</a>
</body>
tag if possible.</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
<body id="top">
<a href="#top" onclick="scrollToTop();return false">Back to Top ↑</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);
}