🛠️ Accordion: Building a library

Hey ,

I'm thrilled to help you learn JavaScript. Unfortunately, you've landed on a page where you cannot access with your current purchase.

Please upgrade (use this link) access this content.

I'm super eager to help you learn more!

🛠️ Accordion: Building a library

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.

// accordion.js
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.

// accordion.js
const accordionContainers = document.querySelectorAll('.accordion-container')

if (accordionContainers.length > 0) {
  accordionContainers.forEach(accordionContainer => {
    // Event listeners here
  })
}

That’s it!