Counter-Meister 0
by WebComponents
HTML
<h1>
<my-counter> Web Component
</h1>
<h2>
Methods: inc, dec, update
</h2>
<my-counter></my-counter>
<h2>GZip analysis:</h2>
<file-size gz src="https://smallesting.github.io/counter.wcdev.min.js"></file-size>
CSS
body{
font:16px Arial;
background:beige;
}
li{
margin-top:.5em;
}
JavaScript
const template = document.createElement('template');
template.innerHTML = `
<style>
* {
font-size: 200%;
}
span {
width: 4rem;
display: inline-block;
text-align: center;
}
button {
width: 4rem;
height: 4rem;
border: none;
border-radius: 10px;
background-color: seagreen;
color: white;
}
</style>
<button id="dec">-</button>
<span id="count"></span>
<button id="inc">+</button>`;
class MyCounter extends HTMLElement {
constructor() {
super();
this.count = 0;
this.attachShadow({ mode: 'open' });
}
connectedCallback() {
this.shadowRoot.appendChild(template.content.cloneNode(true));
this.shadowRoot.getElementById('inc').onclick = () => this.inc();
this.shadowRoot.getElementById('dec').onclick = () => this.dec();
this.update(this.count);
}
inc() {
this.update(++this.count);
}
dec() {
this.update(--this.count);
}
update(count) {
this.shadowRoot.getElementById('count').innerHTML = count;
}
}
customElements.define('my-counter', MyCounter);
// using <file-size> Web Component for Dev.to post
import {} from "https://file-size.github.io/element.js";