A JavaScript class gives a readable way to express a custom element’s behavior and inherit from HTMLElement. Extend that class, then add logic with lifecycle methods such as connectedCallback, which runs when the element is added to the DOM. section 2.4
A slider class
class Slider extends HTMLElement {} starts an empty custom element. Add connectedCallback to give it behavior, then build it out with markup and styling for a slider. section 2.4
Listing 2.3. A complete but simple Web Component example
<html>
<head>
<title>Slider</title>
<script>
class Slider extends HTMLElement {
connectedCallback() {
this.innerHTML = #1
'<div class="bg-overlay"></div><div class="thumb"></div>';
this.style.display = #2
'inline-block';
this.style.position = 'relative';
this.style.width = '500px';
this.style.height = '50px';
this.querySelector('.bg-overlay').style.width = '100%';
this.querySelector('.bg-overlay').style.height = '100%';
this.querySelector('.bg-overlay').style.position = 'absolute';
this.querySelector('.bg-overlay').style.backgroundColor = 'red';
this.querySelector('.thumb').style.marginLeft = '100px';
this.querySelector('.thumb').style.width = '5px';
this.querySelector('.thumb').style.height = 'calc(100% - 5px)';
this.querySelector('.thumb').style.position = 'absolute';
this.querySelector('.thumb').style.border = '3px solid white';
this.querySelector('.thumb').style.borderRadius = '3px';
}
}
if (!customElements.get('wcia-slider')) {
customElements.define('wcia-slider', Slider);
}
</script>
</head>
<body>
<wcia-slider></wcia-slider>
</body>
</html>
A complete example shows a Slider class adding markup and styling when connected to the DOM. section 2.4




















