<button id="backToTop" aria-label="Back to top">⇧</button>
<div style="height: 1500px; padding: 20px;">Scroll down to see the button appear.</div>
#backToTop {
position: fixed;
bottom: 30px;
right: 30px;
width: 50px;
height: 50px;
background: #2563eb;
color: white;
border: none;
border-radius: 50%;
font-size: 1.5rem;
cursor: pointer;
box-shadow: 0 4px 12px rgba(37, 99, 235, 0.4);
opacity: 0;
visibility: hidden;
transition: opacity 0.3s, transform 0.3s, background 0.2s;
z-index: 999;
display: flex;
align-items: center;
justify-content: center;
}
#backToTop.show {
opacity: 1;
visibility: visible;
}
#backToTop:hover {
transform: translateY(-5px);
background: #1d4ed8;
}
const btn = document.getElementById("backToTop");
window.onscroll = function() {
if (document.body.scrollTop > 300 || document.documentElement.scrollTop > 300) {
btn.classList.add("show");
} else {
btn.classList.remove("show");
}
};
btn.addEventListener("click", function() {
window.scrollTo({
top: 0,
behavior: "smooth"
});
});