devops-portfolio / components /back-to-top.js
Mooshie's picture
increase professionalism and interactivity
ec87762 verified
Raw
History Blame Contribute Delete
2.17 kB
class CustomBackToTop extends HTMLElement {
connectedCallback() {
this.attachShadow({ mode: 'open' });
this.shadowRoot.innerHTML = `
<style>
:host {
position: fixed;
bottom: 2rem;
right: 2rem;
z-index: 100;
opacity: 0;
visibility: hidden;
transition: all 0.3s ease;
}
:host.visible {
opacity: 1;
visibility: visible;
}
.back-to-top-btn {
width: 50px;
height: 50px;
background: #EAB308;
border: none;
border-radius: 50%;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
box-shadow: 0 4px 15px rgba(234, 179, 8, 0.3);
transition: all 0.3s ease;
}
.back-to-top-btn:hover {
transform: translateY(-5px);
box-shadow: 0 8px 25px rgba(234, 179, 8, 0.4);
}
.back-to-top-btn svg {
color: black;
transition: transform 0.3s ease;
}
.back-to-top-btn:hover svg {
transform: translateY(-3px);
}
</style>
<button class="back-to-top-btn" id="back-to-top" aria-label="Back to top">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="19" x2="12" y2="5"></line><polyline points="5 12 12 5 19 12"></polyline></svg>
</button>
`;
const btn = this.shadowRoot.getElementById('back-to-top');
// Show/hide button based on scroll position
window.addEventListener('scroll', () => {
if (window.scrollY > 500) {
this.classList.add('visible');
} else {
this.classList.remove('visible');
}
});
// Scroll to top on click
btn.addEventListener('click', () => {
window.scrollTo({
top: 0,
behavior: 'smooth'
});
});
}
}
customElements.define('custom-back-to-top', CustomBackToTop);