Skip to content

Instantly share code, notes, and snippets.

@gartes
Created October 17, 2021 19:22
Show Gist options
  • Save gartes/81b11036282021ca11a5e015cd573181 to your computer and use it in GitHub Desktop.
Save gartes/81b11036282021ca11a5e015cd573181 to your computer and use it in GitHub Desktop.
Web Component Example
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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment