There is such a construction:

<span onclick="toggle(document.getElementById('hide1'))">Кнопка 1</span> <div id="hide1"> Блок 1 </div> 

and

 <span onclick="toggle(document.getElementById('hide2'))">Кнопка 2</span> <div id="hide2"> Блок 2 </div> 

And such a JS:

 function toggle(it) { it.style.display=(it.style.display=="none")?"block":"none"; } 

Many such buttons are planned. How can I realize the ability to turn off the old one with each new open div?

  • one
    keep the current open in a separate variable - Grundy
  • in my right to write the button - Serge Esmanovich
  • I am just learning JS. Tell me, please, the code. - Sergey
  • bootstrap collapse yuzayte - Serge Esmanovich
  • bootstrap will not work for me unfortunately = ( - Sergey

1 answer 1

Best of all. So you need to add that the previous block would hide if it is not the current one, then there will be a glitch.

 var it_last; function toggle(it) { if ((it_last)&&(it!=it_last)) {// скрытие предыдущего it_last.style.display = "none"; } it.style.display= (it.style.display=="none") ? "block" : "none"; it_last = it; }