JSFiddle - React, Tailwind, and code Playground
HTML
<a href="#" id="totop"></a>
CSS
html, body {
height: 3000px;
}
#totop {
position: fixed;
bottom: 10%;
right: 10%;
background: red;
width: 50px;
height: 50px;
cursor: pointer;
opacity: 0;
transition: opacity 0.5s linear;
}
JavaScript
var toTop = document.getElementById('totop'),
duration = 1000;
window.onscroll = function() {
if (window.pageYOffset > document.documentElement.clientHeight) {
toTop.style.opacity = 1;
} else {
toTop.style.opacity = 0;
}
}
toTop.onclick = function(e) {
var start = performance.now();
window.requestAnimationFrame(function foo(time) {
var progress = (time - start) / duration;
window.scrollBy(0, -progress * 1000);
if (window.pageYOffset > 0) {
window.requestAnimationFrame(foo);
}
});
return false;
};