✨feature: Update "back to top" button to work on scroll up after scroll down
This commit is contained in:
@@ -1,23 +1,33 @@
|
||||
// Back to Top Button Component
|
||||
class BackToTopButton extends HTMLElement {
|
||||
connectedCallback() {
|
||||
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;">
|
||||
↑ Top
|
||||
</button>
|
||||
`;
|
||||
const btn = this.querySelector('#backToTopBtn');
|
||||
window.addEventListener('scroll', () => {
|
||||
btn.style.display = window.scrollY > 300 ? 'block' : 'none';
|
||||
});
|
||||
btn.addEventListener('click', () => {
|
||||
window.scrollTo({ top: 0, behavior: 'smooth' });
|
||||
});
|
||||
}
|
||||
connectedCallback() {
|
||||
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;">
|
||||
↑ Top
|
||||
</button>
|
||||
`;
|
||||
|
||||
const btn = this.querySelector('#backToTopBtn');
|
||||
|
||||
let previousScrollY = window.scrollY;
|
||||
|
||||
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() {
|
||||
if (!customElements.get('back-to-top')) {
|
||||
customElements.define('back-to-top', BackToTopButton);
|
||||
}
|
||||
if (!customElements.get('back-to-top')) {
|
||||
customElements.define('back-to-top', BackToTopButton);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user