Created
October 17, 2021 19:22
-
-
Save gartes/81b11036282021ca11a5e015cd573181 to your computer and use it in GitHub Desktop.
Web Component Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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