Code
html
<!-- Using custom elements -->
<my-button color="blue" size="large">
Click Me
</my-button>
<script>
class MyButton extends HTMLElement {
constructor() {
super();
const shadow = this.attachShadow({ mode: 'open' });
const style = document.createElement('style');
style.textContent = `
:host { display: inline-block; }
button {
padding: 8px 16px;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 14px;
background: var(--color, #3498db);
color: white;
}
button:hover { opacity: 0.9; }
button.large { padding: 12px 24px; font-size: 16px; }
`;
const btn = document.createElement('button');
btn.textContent = this.textContent || 'Button';
const color = this.getAttribute('color');
if (color) btn.style.setProperty('--color', color);
const size = this.getAttribute('size');
if (size) btn.classList.add(size);
btn.addEventListener('click', () => {
this.dispatchEvent(new CustomEvent('my-click', {
detail: { message: 'clicked' }
}));
});
shadow.appendChild(style);
shadow.appendChild(btn);
}
// Observe attribute changes
static get observedAttributes() {
return ['color', 'size'];
}
attributeChangedCallback(name, oldVal, newVal) {
// Update button style
}
}
customElements.define('my-button', MyButton);
// Listen for custom events
document.querySelector('my-button')
.addEventListener('my-click', (e) => {
console.log(e.detail.message);
});
</script>