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.
// Copy-paste all the code we wrote here<script type="module" src="main.js"></script>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.
const accordionContainers = document.querySelectorAll('.accordion-container')
accordionContainers.forEach(accordionContainer => { // Event listeners here})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.
const accordionContainers = document.querySelectorAll('.accordion-container')
if (accordionContainers.length > 0) { accordionContainers.forEach(accordionContainer => { // Event listeners here })}Thatβs it!
Welcome! Unfortunately, you donβt have access to this lesson. To get access, please purchase the course or enroll in Magical Dev School.
Unlock this lesson