0

I am trying to make a collapsible div using HTML/JS. Below is my code. It is not having any effect on my page. How come?

Disclaimer : I am new at Javascript and I suck at it, so I suspect I have wired things up incorrectly. Is the onclick event needed here ?

JSFiddle is here (with CSS).

function showhide() {
  var coll = document.getElementsByClassName("content");
  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="row">
  <button class="collapsible" onclick="showhide()">Collapsible</button>
  <div class="content">
    <p>
      This data should be collapsible.
    </p>
  </div>
</div>
Temani Afif
  • 245,468
  • 26
  • 309
  • 415
Simon Kiely
  • 5,880
  • 28
  • 94
  • 180
  • you need to use computed style to test or make the display:block inline initially – Temani Afif Sep 03 '18 at 10:42
  • First step is always to check the dev console (F12 in most browsers) In your fiddle you can see the error `Uncaught ReferenceError: showhide is not defined` I haven't looked into what's causing this, but it's a good place to start. – DBS Sep 03 '18 at 10:42
  • No, you do not want to add a click handler to the content element every time your button gets clicked, that makes little sense. In your function that handles the click on the button, you want to toggle the `display` of the content element. – misorude Sep 03 '18 at 10:42
  • How is this question a duplicate to the one linked as `already has an answer here`? The OP did not ask how to read CSS computed values through JS @TemaniAfif – Jones Joseph Sep 03 '18 at 10:49
  • @JonesJoseph he didn't ask but he's doing it wrong ... the duplicate show how to correctly get the CSS value intially and we need the computed style for this, as the style will not return the correct value since there is no inline styles ... this is not his only issue by the way – Temani Afif Sep 03 '18 at 10:50
  • `this is not his only issue by the way` this is exactly why I asked, how the other answer is the solution to this question... `:)` – Jones Joseph Sep 03 '18 at 10:54
  • @JonesJoseph I am adding more duplicates then – Temani Afif Sep 03 '18 at 10:56

0 Answers0