It’s relatively easy to change the accordion into an Automatic Library. We can toss all the code into an accordion.js file and we’re (almost) done.
// accordion.js
// Copy-paste all the code we wrote here
<script type="module" src="main.js"></script>
// main.js
import './accordion.js'
Supporting multiple instances
We can have multiple accordion instances on the same page. We can support these multiple instances by searching for and looping through all .accordion-container.
If there are no accordion instances on a page, the accordion code will produce an error. We can prevent this error by ensuring accordions are present before adding event listeners.
// accordion.js
const accordionContainers = document.querySelectorAll('.accordion-container')
if (accordionContainers.length > 0) {
accordionContainers.forEach(accordionContainer => {
// Event listeners here
})
}