Skip to content
Advertisement

Why do I have to click twice for this JavaScript function to work?

In order for the fucntion to change the display to “hidden” then back to “block” it requires 2 clicks for each. Why is this? How do I reduce it to just one click?

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

  for (i = 0; i < coll.length; i++) {
    coll[i].addEventListener("click", function() {
      this.classList.toggle("active");
      var content = this.nextElementSibling;
      if (content.style.display === "block") {
        content.style.display = "none";
      } else {
        content.style.display = "block";
      }
    });
  }
}
<div class="offer-row collapsible" id="'.$oid.'" onclick="showOfferMessage()">
    <div class="offer-info-item">
        <div class="offcatreview-title">
            <h3>Cat. Rating</h3>
        </div>
        <div class="offer-cat-rating">
        </div>
    </div>
</div>
<div class="content">
    <p>'.$message.'</p>
</div>

Advertisement

Answer

That’s because you’re registering an event listener on every click! So your listener executes once more every time you click.

Your code fixed:

                    
function showOfferMessage(element) {
    element.classList.toggle("active");
    var content = element.nextElementSibling;
    if (content.style.display === "block") {
      content.style.display = "none";
    } else {
      content.style.display = "block";
    }
}
<div class="offer-row collapsible" id="'.$oid.'" onclick="showOfferMessage(this)">
    <div class="offer-info-item">
        <div class="offcatreview-title">
            <h3>Cat. Rating</h3>
        </div>
        <div class="offer-cat-rating">
        </div>
    </div>
</div>
<div class="content" style="display: block">
    <p>'.$message.'</p>
</div>
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement