LauraMDB's picture
create a drop down with options:
05382ed verified
class CustomDropdown extends HTMLElement {
connectedCallback() {
this.attachShadow({ mode: 'open' });
this.shadowRoot.innerHTML = `
<style>
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-btn {
background: none;
border: none;
cursor: pointer;
color: #374151;
font-weight: 500;
transition: color 0.2s;
display: flex;
align-items: center;
gap: 0.25rem;
}
.dropdown-btn:hover {
color: #13aa52;
}
.dropdown-content {
position: absolute;
background-color: white;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.1);
border-radius: 0.5rem;
z-index: 1;
opacity: 0;
visibility: hidden;
transform: translateY(10px);
transition: all 0.2s ease;
}
.dropdown-content.show {
opacity: 1;
visibility: visible;
transform: translateY(0);
}
.dropdown-content a {
color: #374151;
padding: 0.75rem 1rem;
text-decoration: none;
display: block;
transition: background-color 0.2s;
font-size: 0.875rem;
}
.dropdown-content a:hover {
background-color: #f3f4f6;
color: #13aa52;
}
.icon {
transition: transform 0.2s;
}
.dropdown.active .icon {
transform: rotate(180deg);
}
</style>
<div class="dropdown">
<button class="dropdown-btn">
<span>${this.getAttribute('title') || 'Menu'}</span>
<svg class="icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<polyline points="6 9 12 15 18 9"></polyline>
</svg>
</button>
<div class="dropdown-content">
<slot></slot>
</div>
</div>
`;
const dropdownBtn = this.shadowRoot.querySelector('.dropdown-btn');
const dropdownContent = this.shadowRoot.querySelector('.dropdown-content');
const dropdown = this.shadowRoot.querySelector('.dropdown');
dropdownBtn.addEventListener('click', (e) => {
e.stopPropagation();
dropdownContent.classList.toggle('show');
dropdown.classList.toggle('active');
});
// Close when clicking outside
document.addEventListener('click', () => {
dropdownContent.classList.remove('show');
dropdown.classList.remove('active');
});
}
}
customElements.define('custom-dropdown', CustomDropdown);