mardi 30 juillet 2019

what's wrong with my javascript code? (display toggle)

i made a button that makes my div hide and visible. It works well once or twice but and then It doesn't (I click the button with column1 doesn't open the column 1's hidden div then I click the column2 column2's hidden div is opening....)

<style>
  div {
    display: none;
  }
  
  div.hidden,
  li.on div.hidden {
    display: none;
  }
  
  li.on div {
    display: block;
  }
</style>
</head>

<body>
  <ul>
    <li class="on">column1
      <div>box</div>
      <div>box</div>
      <div>box</div>
      <div class="hidden">box</div>
      <div class="hidden">box</div>
      <div class="hidden">box</div>
    </li>
    <li>column2
      <div>box</div>
      <div>box</div>
      <div>box</div>
      <div class="hidden">box</div>
      <div class="hidden">box</div>
      <div class="hidden">box</div>
    </li>
    <li>column3
      <div>box</div>
      <div>box</div>
      <div>box</div>
      <div class="hidden">box</div>
      <div class="hidden">box</div>
      <div class="hidden">box</div>
    </li>
  </ul>
  <button>click!</button>
  <script>
    var tabList = document.querySelectorAll("li");

    tabList.forEach(function(tab, index) {
      tab.addEventListener('click', function() {
        removeOther();
        tab.classList.toggle("on");
        btnEvent(tab);
      });
    });

    function removeOther() {
      for (var i = 0; i < tabList.length; i++) {
        if (tabList[i].classList.contains("on")) {
          tabList[i].classList.remove("on");
        }
      }
    }

    var btn = document.getElementsByTagName("button")[0];

    function btnEvent(tab) {
      var hiddenTabs = tab.querySelectorAll('.hidden');
      btn.addEventListener("click", function() {
        for (var i = 0; i < hiddenTabs.length; i++) {
          hiddenTabs[i].classList.toggle("hidden");
        }
      })
    }
  </script>
</body>

It seems works well but when I try 3 or more times then the button is not work well




Aucun commentaire:

Enregistrer un commentaire