JSFiddle - React, Tailwind, and code Playground
HTML
<div class="container">
<p>please scroll down</p>
<button id="float-button">TOP</button>
</div>
CSS
#float-button {
position:fixed;
right: calc(50% - (100px / 2));
top: calc(100% - 30px);
height: 30px;
width: 100px;
border: none;
background: #6274d0;
color: white;
border-top-left-radius: 8px;
border-top-right-radius: 8px;
display: none;
}
.container {
height: 1000px;
background: #ccc;
}
JavaScript
const floatBtn = document.getElementById('float-button');
window.addEventListener(
'scroll',
() => {
if (window.scrollY > 50) {
floatBtn.style = 'display: block;'
} else {
floatBtn.style = 'display: none;'
}
},
{passive: true}
);
floatBtn.addEventListener(
'click',
() => {
window.scrollTo({
top: 0,
behavior: 'smooth'
});
}
);