Last active
July 3, 2024 13:29
-
-
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/
This file contains 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
/* 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; | |
} |
This file contains 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
/* 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', | |
}); |
This file contains 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
<!-- 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