Back-to-Top Button
Injects a fixed back-to-top button that appears after scrolling 400px and scrolls to the top on click.
JavaScriptby SnipCraft
js
(function () {
'use strict';
document.addEventListener('DOMContentLoaded', function () {
var btn = document.createElement('button');
btn.id = 'back-to-top';
btn.setAttribute('aria-label', 'Back to top');
btn.innerHTML = '⇧';
btn.style.cssText = [
'position:fixed',
'bottom:2rem',
'right:2rem',
'width:44px',
'height:44px',
'border-radius:50%',
'background:#3b82f6',
'color:#fff',
'border:none',
'font-size:1.5rem',
'cursor:pointer',
'opacity:0',
'transition:opacity 0.3s',
'z-index:999',
'pointer-events:none'
].join(';');
document.body.appendChild(btn);
window.addEventListener('scroll', function () {
if (window.scrollY > 400) {
btn.style.opacity = '1';
btn.style.pointerEvents = 'auto';
} else {
btn.style.opacity = '0';
btn.style.pointerEvents = 'none';
}
}, { passive: true });
btn.addEventListener('click', function () {
window.scrollTo({ top: 0, behavior: 'smooth' });
});
});
})();#button#javascript#navigation#scroll#ux