Welcome to our comprehensive guide on HTML Web Components! In this tutorial, we'll delve into the world of reusable and customizable parts of a web page, making your coding life easier and more efficient.
Web Components are a set of web platform APIs that allow you to create reusable and encapsulated custom HTML tags. They enable you to create custom elements, shadow DOM, and other functionalities, making web development more modular and efficient.
Let's create a simple custom element called my-button.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My Custom Element</title>
</head>
<body>
<script>
class MyButton extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
this.shadowRoot.innerHTML = `
<button>Click me!</button>
`;
}
}
customElements.define('my-button', MyButton);
// Create an instance of our custom element
document.body.appendChild(document.createElement('my-button'));
</script>
</body>
</html>š Note: The customElements.define() method is used to create a custom element, and MyButton is our custom element class that extends the built-in HTMLElement class.
Web Components provide a feature called Shadow DOM, which allows you to style your custom elements without affecting the rest of the page.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My Custom Element with Styles</title>
<style>
my-button {
--primary-color: blue;
font-size: 20px;
background-color: var(--primary-color);
padding: 10px;
}
</style>
</head>
<body>
<script>
class MyButton extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
this.shadowRoot.innerHTML = `
<button>Click me!</button>
`;
}
connectedCallback() {
this.shadowRoot.style.setProperty('--primary-color', this.getAttribute('color') || 'blue');
}
}
customElements.define('my-button', MyButton);
// Create an instance of our custom element with a custom color
document.body.appendChild(document.createElement('my-button'));
document.querySelector('my-button').setAttribute('color', 'red');
</script>
</body>
</html>š Note: We've created a custom style rule for our my-button element and defined a custom property --primary-color. In the JavaScript, we're using the connectedCallback() method to apply the custom color attribute to the style rule.
What are Web Components?
By the end of this tutorial, you'll have a solid understanding of HTML Web Components and be ready to start creating your own custom elements! Happy coding! š