Skip to content

Instantly share code, notes, and snippets.

@james2doyle
Last active April 12, 2023 22:08
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/3a24361e1de1d35b850a42eab1be92f9 to your computer and use it in GitHub Desktop.
Save james2doyle/3a24361e1de1d35b850a42eab1be92f9 to your computer and use it in GitHub Desktop.
An example of a custom element that can toggle the content within in. Demo: https://stackblitz.com/edit/js-toggle-custom-element or https://js-toggle-custom-element.stackblitz.io/
/* Demo: https://js-toggle-custom-element.stackblitz.io/ */
[is='toggle-container'] > *:not([is='toggle-button']) {
display: none;
}
[is='toggle-container'][open] > *:not([is='toggle-button']) {
display: block;
}
/* Demo: https://js-toggle-custom-element.stackblitz.io/ */
class ToggleContainer extends HTMLDivElement {
// A getter/setter for an open property.
get open() {
return this.hasAttribute('open');
}
set open(val) {
// Reflect the value of the open property as an HTML attribute.
if (val) {
this.setAttribute('open', '');
} else {
this.removeAttribute('open');
}
}
// A getter/setter for a disabled property.
get disabled() {
return this.hasAttribute('disabled');
}
set disabled(val) {
// Reflect the value of the disabled property as an HTML attribute.
if (val) {
this.setAttribute('disabled', '');
} else {
this.removeAttribute('disabled');
}
}
toggleDrawer() {
if (!this.disabled) {
this.open = !this.open;
}
}
}
customElements.define('toggle-container', ToggleContainer, {
extends: 'div',
});
class ToggleDrawerButton extends HTMLButtonElement {
constructor() {
super();
this.addEventListener('click', (e) => {
this.closest('[is=toggle-container]').toggleDrawer();
});
}
}
customElements.define('toggle-button', ToggleDrawerButton, {
extends: 'button',
});
<!-- demo: https://js-toggle-custom-element.stackblitz.io/ -->
<div is="toggle-container">
<button is="toggle-button" title="Press me to toggle content that is not me">Toggle</button>
<p>Content that will be toggled</p>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment