feature: Update "back to top" button to work on scroll up after scroll down

This commit is contained in:
Keith Solomon
2026-03-09 09:05:53 -05:00
parent 5b7fed2cb8
commit 9bde54a41c
+27 -17
View File
@@ -1,23 +1,33 @@
// Back to Top Button Component // Back to Top Button Component
class BackToTopButton extends HTMLElement { class BackToTopButton extends HTMLElement {
connectedCallback() { connectedCallback() {
this.innerHTML = ` this.innerHTML = `
<button id="backToTopBtn" aria-label="Back to top" class="back-to-top" style="display:none;position:fixed;bottom:2rem;right:2rem;z-index:1000;padding:0.75em 1.5em;font-size:1.1rem;border-radius:2em;background:var(--color-primary,#3857BC);color:#fff;border:none;box-shadow:0 2px 8px rgba(0,0,0,0.15);cursor:pointer;transition:opacity 0.2s;"> <button id="backToTopBtn" aria-label="Back to top" class="back-to-top" style="display:none;position:fixed;bottom:2rem;right:2rem;z-index:1000;padding:0.75em 1.5em;font-size:1.1rem;border-radius:2em;background:var(--color-primary,#3857BC);color:#fff;border:none;box-shadow:0 2px 8px rgba(0,0,0,0.15);cursor:pointer;transition:opacity 0.2s;">
↑ Top ↑ Top
</button> </button>
`; `;
const btn = this.querySelector('#backToTopBtn');
window.addEventListener('scroll', () => { const btn = this.querySelector('#backToTopBtn');
btn.style.display = window.scrollY > 300 ? 'block' : 'none';
}); let previousScrollY = window.scrollY;
btn.addEventListener('click', () => {
window.scrollTo({ top: 0, behavior: 'smooth' }); window.addEventListener('scroll', () => {
}); const currentScrollY = window.scrollY;
} const isScrollingUp = currentScrollY < previousScrollY;
const shouldShowButton = currentScrollY > 300 && isScrollingUp;
btn.style.display = shouldShowButton ? 'block' : 'none';
previousScrollY = currentScrollY;
});
btn.addEventListener('click', () => {
window.scrollTo({ top: 0, behavior: 'smooth' });
});
}
} }
export function registerBackToTopButton() { export function registerBackToTopButton() {
if (!customElements.get('back-to-top')) { if (!customElements.get('back-to-top')) {
customElements.define('back-to-top', BackToTopButton); customElements.define('back-to-top', BackToTopButton);
} }
} }