HTML
Web Components
Custom elements and Shadow DOM.
By EZ4Code Team
web-componentscomponent
Code
<!-- 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>Explanation
Web Components define custom elements via customElements; Shadow DOM isolates styles; slot projects content.
More HTML Snippets
Accessible Form with Inputs
Build an accessible HTML form with labels, inputs, select, and checkbox.
Table with Thead Tbody Tfoot
Structure tabular data with thead, tbody, tfoot, and caption in HTML.
Responsive Images and Video
Embed responsive images with srcset, video, audio, and figure in HTML.
Links Anchors and Download
Create internal, external, anchor, email, phone, and download links in HTML.
Semantic Tags
HTML5 semantic structure.
Form Validation
HTML5 form validation.