Home > Enterprise >  Open hidden elements one at a time?
Open hidden elements one at a time?

Time:09-11

please I am trying to create a FAQ like functionality, I have some elements hidden so when I click on a button it opens and hides it. I have been able to do this but I am not getting what I actually want. I might have done something wrong I suppose. So, there are 5 elements with the same className, this will help me target them all and run a for loop to kind of break them apart. However if I click on this button to open one of the element the other ones open.

const openBtn = document.querySelectorAll(".openBtn")
const openContent = document.querySelectorAll(".openContent")

for(btn of openBtn) {
    btn.addEventListener('click', () => {
        for(content of openContent) {
            if (content.classList.contains('hidden')) {
                content.classList.remove('hidden');
                content.classList.add('flex')
            } else {
                content.classList.remove('flex');
                content.classList.add('hidden')
            }
        }
    })
}

So as you can see, If I click on the chevron icon for just one of the wither About Us, Careers or just any of the 5 every other one opens. How do I fix this ?

So as you can see, If I click on the chevron icon for just one of the wither About Us, Careers or just any of the 5 every other one opens. How do I fix this ?

CodePudding user response:

Since you aren't going to post even the most general version of your HTML, here is a general outline.

First, each button gets a data attribute for target,then each FAQ div gets an ID attribute that matches the data target attribute.

I attach the click handler to the target and look for openBTN on the clicked element. Then I loop through every OPENED div to close it. Then I get the target data attribute and add the appropriate classes.

document.addEventListener("click", function(e) {
  if (e.target.classList.toString().includes("openBtn")) {

    let opened = document.querySelectorAll(".openContent.flex");

    opened.forEach(function(el) {
      el.classList.add("hidden");
      el.classList.remove("flex");
    });
    let target = document.querySelector(e.target.dataset.target)
    target.classList.remove("hidden");
    target.classList.add("flex");
  }
});
.hidden {
  display: none
}
<button data-target="#faq1" >OPEN</button>
<div id="faq1" >1</div>

<button data-target="#faq2" >OPEN</button>
<div id="faq2" >2</div>

<button data-target="#faq3" >OPEN</button>
<div id="faq3" >3</div>

<button data-target="#faq4" >OPEN</button>
<div id="faq4" >4</div>

  • Related