JSFiddle - React, Tailwind, and code Playground
HTML
<h1>Top of Page</h1>
<p><em>Try scrolling and vertically resizing the window.</em></p>
<ul>
<li>List Item</li>
<li>List Item</li>
<li>List Item</li>
<li>List Item</li>
<li>List Item</li>
<li>List Item</li>
<li>List Item</li>
<li>List Item</li>
<li>List Item</li>
<li>List Item</li>
<li>List Item</li>
<li>List Item</li>
<li>List Item</li>
<li>List Item</li>
<li>List Item</li>
<li>List Item</li>
<li>List Item</li>
<li>List Item</li>
<li>List Item</li>
<li>List Item</li>
<li>List Item</li>
<li>List Item</li>
<li>List Item</li>
<li>List Item</li>
<li>List Item</li>
<li>List Item</li>
<li>List Item</li>
<li>List Item</li>
<li>List Item</li>
<li>List Item</li>
<li>List Item</li>
<li>List Item</li>
</ul>
<h2>Bottom of page</h2>
<button id="toTopBtn" disabled="true">Back to Top</button>
CSS
#toTopBtn {
opacity: 1;
transition: 0.2s ease;
cursor: pointer;
position: fixed;
bottom: 20px;
right: 20px;
padding: 20px 25px;
border-radius: 10px;
background: white;
border: none;
box-shadow: 2px 8px 30px rgba(0, 0, 0, 0.25);
display: block;
appearance: none;
user-select: none;
color: black;
}
#toTopBtn:hover {
color: blue;
}
#toTopBtn:active {
color: black;
}
#toTopBtn[disabled] {
opacity: 0;
cursor: default;
color: black;
}
JavaScript
const toTopBtn = document.getElementById('toTopBtn');
toTopBtn.addEventListener('click', () => {
window.scroll({
top: 0,
left: 0,
behavior: 'smooth'
});
toTopBtn.disabled = true;
});
window.addEventListener('scroll', () => {
if (window.scrollY > 0) {
toTopBtn.disabled = false;
} else {
toTopBtn.disabled = true;
}
}, true);