EmilAv
EmilAv

Reputation: 17

CSS Accordion and JavaScript not working as expected

I am trying to build the FAQ section of my company's website. The FAQ is using a drop down menu for each question -> when the "+" is clicked the answer is shown and that changes to "-". When I close the question I expect "-" to turn into "+" but it doesn't until I click on a different question, than it changes.

Here is my code:

var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
  acc[i].addEventListener("click", function() {

    var panel = this.nextElementSibling;
    if (panel.style.maxHeight){
      panel.style.maxHeight = null;
    } else {
      let active = document.querySelectorAll(".accordion-div .accordion.active");
      for(let j = 0; j < active.length; j++){
        active[j].classList.remove("active");
        active[j].nextElementSibling.style.maxHeight = null;
      }
      this.classList.toggle("active");
      panel.style.maxHeight = panel.scrollHeight + "px";
    }
  });
}
.accordion {
  cursor: pointer;
  background-color:#ffffff;
  color: #082f55;
padding-left: 10px;
  padding-top: 18px;
  padding-right: 18px;
padding-bottom: 0px;
  width: 100%;
font-weight: bold;
  border: none;
  text-align: left;
  outline: none;
  transition: all 0.5s;
}
.accordion:hover {
  color: #b0cb1f;
}
.accordion:after {
  content: "\02795";
  font-size: 13px;
  float: right;
  margin-left: 5px;
}

.active:after{
  content: "\2796";
}

.panel {
  width: 100%;
  margin-right: auto;
  margin-left: auto;
  max-height: 0;
  transition: max-height 0.5s;
  overflow: hidden;
}

.answer{
margin-top: 10px;
  padding-left: 30px;
  padding-right: 50px;
}

.horLine{
margin-top: 18px;
  border-bottom: 1px groove;
}

Can someone help?

Upvotes: 1

Views: 202

Answers (1)

Jeith
Jeith

Reputation: 395

It's a little tricky to resolve this one without the HTML, but I believe you should be using jQuery's toggleClass() instead of toggle(). Try rewriting this line with toggle:

this.classList.toggle("active");

into this:

this.classList.toggleClass("active");

.toggleClass() will switch between classes like you want, and .toggle() is for toggling between .hide() & .show() for the selected element.

Upvotes: 1

Related Questions