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: all 0.5s linear;
visibility: hidden;
}
#totop.show {
opacity: 1;
visibility: visible;
}
JavaScript
var toTop = document.getElementById('totop'),
toTopIsVisible = false,
duration = 1000;
window.onscroll = function() {
if (window.pageYOffset > document.documentElement.clientHeight != toTopIsVisible) {
toTopIsVisible = !toTopIsVisible;
toTop.classList.toggle('show', toTopIsVisible);
}
}
toTop.onclick = function(e) {
var begin = performance.now(),
startY = window.pageYOffset;
window.requestAnimationFrame(function foo(time) {
var y = startY - (startY / duration * (time - begin));
window.scrollTo(0, y);
if(y > 0) {
window.requestAnimationFrame(foo);
}
else alert(time-begin);
});
return false;
};