Web components are a set of powerful tools that allow you to create your own custom HTML elements. These elements can be used just like any other HTML tag (e.g., <div>
, <span>
) but with your own special behavior and design.
The core technologies behind web components are:
- Custom Elements: Allows you to define new HTML tags.
- Shadow DOM: Keeps your element’s structure and styles isolated from the rest of the page.
- HTML Templates: Lets you define reusable HTML that isn’t rendered until you use it.
In this guide, we'll build a simple counter component from scratch. This counter will have buttons to increase and decrease a number.
The component will look like this:
Here is the link for final version with all the source code.
Prerequisites
Before we begin, here’s what you need to know:
- Basic JavaScript.
- A simple understanding of how the DOM (Document Object Model) works (don’t worry if you’re not an expert — we’ll cover what you need).
Setting Up the Project
First, let’s set up a simple project with two files:
-
counter.html
: The HTML file that will hold the page structure. -
counter.js
: The JavaScript file where we define our custom counter element.
counter.html
This file contains the basic HTML structure of your page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width" />
<title>Counter Component</title>
<script src="./counter.js"></script>
</head>
<body>
<!-- The counter component will be inserted here -->
</body>
</html>
Creating the Template
A template is just a way to define the structure of our custom element (like what it looks like). Let’s create one for our counter:
counter.html
(Add the Template)
<body>
<template id="x-counter">
<div>
<button id="min-btn">-</button>
<span id="counter-display">0</span>
<button id="plus-btn">+</button>
</div>
</template>
</body>
Here’s what each part of this template does:
-
<button id="min-btn">-</button>
: A button to decrease the counter. -
<span id="counter-display">0</span>
: A place to show the current counter value. -
<button id="plus-btn">+</button>
: A button to increase the counter.
This template will not show up on the page directly. We will use it later to create our custom element.
Defining the Custom Counter Element
Now, we’ll write the JavaScript to define how our counter works. We’ll create a class that extends the basic HTMLElement
, which is what all HTML elements are built on.
counter.js
class XCounter extends HTMLElement {
constructor() {
super();
this.counter = 0; // Start the counter at 0
this.elements = {}; // To store references to our buttons and display
}
connectedCallback() {
// This runs when the element is added to the page
const template = document.getElementById("x-counter");
this.attachShadow({ mode: "open" });
// Clone the template and add it to our custom element's shadow DOM
this.shadowRoot.appendChild(template.content.cloneNode(true));
// Get references to the buttons and display
this.elements = {
plusBtn: this.shadowRoot.querySelector("#plus-btn"),
minBtn: this.shadowRoot.querySelector("#min-btn"),
counterDisplay: this.shadowRoot.querySelector("#counter-display")
};
// Show the initial counter value
this.displayCount();
// Add event listeners for the buttons
this.elements.plusBtn.onclick = () => this.increment();
this.elements.minBtn.onclick = () => this.decrement();
}
increment() {
this.counter += 1;
this.displayCount();
}
decrement() {
this.counter -= 1;
this.displayCount();
}
displayCount() {
this.elements.counterDisplay.textContent = this.counter;
}
}
// Register the custom element so we can use it in HTML
customElements.define("x-counter", XCounter);
Breaking it Down:
The
constructor
: This is where we set up initial values for our counter and store references to the elements inside the counter.-
connectedCallback
: This function runs when the custom element is added to the page. Here, we:- Attach a shadow DOM to keep our element’s structure and styles separate from the rest of the page.
- Clone the template we created earlier and add it to the shadow DOM.
- Set up references to the plus and minus buttons and the display where the counter is shown.
increment
anddecrement
: These functions change the value of the counter by 1 and update the display.displayCount
: This function updates the text inside the<span>
to show the current counter value.Register the element: Finally, we tell the browser to recognize
<x-counter>
as a custom element that uses theXCounter
class.
Using the Counter Component
Now that our counter is defined, we can use it just like any other HTML element. Here’s how to add it to the page:
counter.html
(Add the Custom Element)
<body>
<x-counter></x-counter>
<template id="x-counter">
...
</template>
</body>
This will create a counter on the page with two buttons — one to increase and one to decrease the number. The counter will start at 0, and you can interact with it by clicking the buttons.
Style the element
Styling can be done in a few ways, but when using the Shadow DOM, we can encapsulate the styles to ensure they don’t interfere with other parts of the page. In this section, we will style our counter element using adopteStyleSheet.
counter.js with Styling
...
connectedCallback() {
...
this.attachShadow({ mode: 'open' });
// Add styles to the component
const sheet = new CSSStyleSheet();
sheet.replaceSync(this.styles());
this.shadowRoot.adoptedStyleSheets = [sheet];
// Clone the template and add it to our custom element's shadow DOM
this.shadowRoot.appendChild(template.content.cloneNode(true));
...
}
...
styles() {
return `
:host {
display: block;
border: dotted 3px #333;
width: fit-content;
height: fit-content;
padding: 15px;
}
button {
border: solid 1px #333;
padding: 10px;
min-width: 35px;
background: #333;
color: #fff;
cursor: pointer;
}
button:hover {
background: #222;
}
span {
display: inline-block;
padding: 10px;
width: 50px;
text-align: center;
}
`
}
...
...
Conclusion
In this tutorial, we learned how to create a simple web component:
- We used an HTML template to define the structure of our custom element.
- We added shadow DOM to isolate the styles and behavior of our component.
- We wrote JavaScript to control the logic of the counter (increment, decrement, and display the count).
Web components are a great way to make your web applications more modular and reusable.
Top comments (0)