Why is does the toggle function only work after double clicking? (Javascript, CSS)

Viewed 55

Following this w3 guide to creating collapsible divs, but inside a React app. The cards I made only collapse after double clicking instead of single clicking. The only difference I can find is that I'm not using <script> and instead using onClick={function}.

Here's my code:

At top of Card component file:

function collapseElement() {
  var coll = document.getElementsByClassName("collapsible");
  var i;

  for (i = 0; i < coll.length; i++) {
    coll[i].addEventListener("click", function() {
      console.log(i);
      this.classList.toggle("active");
      var content = this.nextElementSibling;
      if (content.style.display === "block") {
        content.style.display = "none";
      } else {
        content.style.display = "block";
      }
    });
  }
}

In Card Component:

<div>
    <button type="button" className="collapsible" onClick={collapseElement}>
        <div className="collapsible-title">
          {props.title}
        </div>
    </button>

    <div className="content">
      {props.children}
    </div>

</div>

and the CSS:

.collapsible {
  background-color: #777;
  color: white;
  cursor: pointer;
  padding: 18px;
  width: 100%;
  border: none;
  text-align: left;
  outline: none;
  font-size: 15px;
}

.active, .collapsible:hover {
  background-color: #555;
}

.content {
  padding: 0 18px;
  max-height: 0;
  overflow: hidden;
  transition: max-height 0.2s ease-out;
  background-color: #f1f1f1;
}

Thanks in advance!

1 Answers

You've set up the button's onClick to run collapseElement, which then goes through a list of elements with the "collapsible" class, and adds another click-event-listener to them to do the collapsing.

Either just run that function that adds a new click listener to every item, or just split out the actual function that toggles the content, and give that as the onClick tag.

Related