Home > Back-end >  javascript toggle not working when the remove exist
javascript toggle not working when the remove exist

Time:12-07

In the code below I remove all the active classes from the div box then i add the active class for the current one using the toggle

all of that work fine

but the problem is when I click on the same box, for example, box1 it doesn't remove the active class I should click on the second one to remove it and in my code, I use the toggle, not the add.

I want when I click on a box the box open and when I click again on it it should be close again and if I click on another box after the first box should be close

what's wrong with my code?

let faqs = document.querySelectorAll(".allsector .box");

faqs.forEach((faq) => {
    faq.addEventListener("click", function (e) {
        faqs.forEach((ele) => {
            ele.classList.remove("active");
        });
        faq.classList.toggle("active");
    });
});
.allsector .box .content {
    max-height: 0;
    visibility: hidden;
    opacity: 0;
    transition: all .5s ease-in-out;
}

.allsector .box.active .content {
    max-height: 300px;
    visibility: visible;
    opacity: 1;
    }
    
.allsector .box.active .fa-angle-down {
    transform: rotate(180deg);
}
<script src="https://kit.fontawesome.com/9e5ba2e3f5.js" crossorigin="anonymous"></script>
<div class="allsector">
<div class="box">
<div class="title">title 1 <i class="fas fa-angle-down"></i></div>
<div class="content">content 1</div>
</div>
<div class="box">
<div class="title">title 2 <i class="fas fa-angle-down"></i></div>
<div class="content">content 2</div>
</div>
<div class="box">
<div class="title">title 3 <i class="fas fa-angle-down"></i></div>
<div class="content">content 3</div>
</div>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Remove forEach, use this:

let faqs = document.querySelectorAll(".allsector .box");

    faqs.forEach((faq) => {
        faq.addEventListener("click", function (e) {
            faq.classList.toggle("active");
        });
    });

CodePudding user response:

Remove forEach from addEventListener.

let faqs = document.querySelectorAll(".allsector .box");

faqs.forEach((faq) => {
 faq.addEventListener("click", function (e) {
    faq.classList.toggle("active");
 });
});
  • Related