Last active
March 17, 2024 15:03
-
-
Save jasondmoss/2ee28c3d758f1e814a44a743ef88aaf2 to your computer and use it in GitHub Desktop.
Custom Web Component to 'progressively enhance' the <details> element.
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
/** | |
* Custom Web Component to 'progressively enhance' the <details> element used | |
* with our form filters. | |
* | |
* @author Jason D. Moss <[email protected]> | |
* @copyright 2024 Jason D. Moss. All rights reserved. | |
* | |
* @see https://developer.mozilla.org/en-US/docs/Web/API/Web_components | |
* | |
* <details> | |
* <summary>Details label</summary> | |
* <div> | |
* Details content. | |
* </div> | |
* </details> | |
*/ | |
export class Accordion extends HTMLElement { | |
constructor () { | |
// Inherit class properties. | |
super(); | |
// Cache instance for use in function. | |
let instance = this; | |
// Setup handler function. | |
this.handler = (event) => { | |
// Only run if accordion is open. | |
if (! event.target.hasAttribute("open")) { | |
return; | |
} | |
// Get all open accordions inside parent. | |
let opened = instance.querySelectorAll("details[open]"); | |
// Close open ones that aren't current accordion. | |
for (let accordion of opened) { | |
if (accordion === event.target) { | |
continue; | |
} | |
accordion.removeAttribute("open"); | |
} | |
}; | |
} | |
// Runs each time the element is appended to or moved in the DOM. | |
connectedCallback () { | |
this.addEventListener("toggle", this.handler, true); | |
} | |
// Runs when the element is removed from the DOM. | |
disconnectedCallback () { | |
this.removeEventListener("toggle", this.handler, true); | |
} | |
} | |
/* <> */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment