Skip to content

Instantly share code, notes, and snippets.

@Braden-Preston
Last active November 14, 2023 04:45
Show Gist options
  • Save Braden-Preston/e4fac5dc7df5c0348a8ab9321d65a602 to your computer and use it in GitHub Desktop.
Save Braden-Preston/e4fac5dc7df5c0348a8ab9321d65a602 to your computer and use it in GitHub Desktop.
Tailwind Web Component
z-counter::part(root) {
@apply font-bold flex flex-col gap-2 items-center text-gray-600;
}
z-counter::part(count) {
@apply text-4xl leading-none;
}
z-counter::part(title) {
@apply max-w-fit text-lg flex gap-4;
}
z-counter::part(actions) {
@apply flex flex-row gap-4;
}
z-counter::part(btn) {
@apply text-white font-bold bg-indigo-500 rounded-lg border-0 w-8 py-2;
}
const template = document.createElement("template");
template.innerHTML = `
<div part="root">
<div part="title">Count:</div>
<span part="count" id="count"></span>
<div part="actions">
<button part="btn" id="dec">-</button>
<button part="btn" id="inc">+</button>
</div>
</div>
`;
class Counter 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").textContent = count;
}
}
customElements.define("z-counter", Counter);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment