UPDATE
Going to top of the page with a scroll effect is a bit more easier in javascript now with:
https://developer.mozilla.org/en-US/docs/Web/API/Window/scroll
There are 2 ways to use scroll API
.
This is the method I recommend. Using an option object:
window.scroll(options)
This is a better option since you can define a behavior
prop which applies a built-in easing animation.
window.scroll({
top: 0,
left: 0,
behavior: 'smooth'
});
The other method is to use an x and y coordinates.
window.scroll(x-coord, y-coord)
x-coord - is the pixel along the horizontal axis of the document that you want displayed in the upper left.
y-coord - is the pixel along the vertical axis of the document that you want displayed in the upper left.
OLD ANSWER DO NOT USE
This is our vanilla javascript
implementation. It has a simple easing effect so that the user doesn't get shocked after clicking the To Top button.
Its very small and gets even smaller when minified. Devs looking for an alternative to the jquery method but want the same results can try this.
JS
document.querySelector("#to-top").addEventListener("click", function(){
var toTopInterval = setInterval(function(){
var supportedScrollTop = document.body.scrollTop > 0 ? document.body : document.documentElement;
if (supportedScrollTop.scrollTop > 0) {
supportedScrollTop.scrollTop = supportedScrollTop.scrollTop - 50;
}
if (supportedScrollTop.scrollTop < 1) {
clearInterval(toTopInterval);
}
}, 10);
},false);
HTML
<button id="to-top">To Top</button>
Cheers!