Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save james2doyle/94172cfc77fb5eea5b06b2f5e615a93b to your computer and use it in GitHub Desktop.
Save james2doyle/94172cfc77fb5eea5b06b2f5e615a93b to your computer and use it in GitHub Desktop.
An example of a custom element that can toggle a state which can be used to control the elements. Demo: https://stackblitz.com/edit/stateful-switch-custom-element or https://stateful-switch-custom-element.stackblitz.io/
stateful-switch > *:not([switch-active]) {
display: none;
}
<stateful-switch default="all">
<p switch-case="all">Showing <span>"all"</span></p>
<p switch-case="some">Showing <span>"some"</span></p>
<p switch-case="none">Showing <span>"none"</span></p>
<button is="stateful-switch-button" switch-case="all" value="none">
Set to "none"
</button>
<button is="stateful-switch-button" switch-case="all" value="some">
Set to "some"
</button>
<button is="stateful-switch-button" switch-case="none" value="all">
Set to "all"
</button>
<button is="stateful-switch-button" switch-case="some" value="all">
Set to "all"
</button>
</stateful-switch>
class StatefulSwitch extends HTMLElement {
get value() {
return this.getAttribute('value') || this.getAttribute('default') || '';
}
set value(val) {
if (val) {
this.setAttribute('value', String(val));
} else {
this.setAttribute('value', String(this.getAttribute('default') || ''));
}
if (!this.disabled) {
this.update();
}
}
get disabled() {
return this.hasAttribute('disabled');
}
set disabled(val) {
if (val) {
this.setAttribute('disabled', '');
} else {
this.removeAttribute('disabled');
}
}
constructor() {
super();
if (!this.disabled) {
this.update();
}
}
update() {
const elems = this.querySelectorAll('[switch-case]');
if (elems) {
elems.forEach((el) => {
const condition = el.getAttribute('switch-case');
if (condition === this.value) {
el.setAttribute('switch-active', '');
} else {
el.removeAttribute('switch-active');
}
});
}
}
}
customElements.define('stateful-switch', StatefulSwitch);
class StatefulSwitchButton extends HTMLButtonElement {
get value() {
return this.getAttribute('value');
}
get trigger() {
return this.getAttribute('trigger') || 'click';
}
constructor() {
super();
this.addEventListener(this.trigger, (e) => {
this.closest('stateful-switch').value = this.value;
});
}
}
customElements.define('stateful-switch-button', StatefulSwitchButton, {
extends: 'button',
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment