Search code examples
javascriptjqueryshow-hide

Add hide for all other buttons in functions jQuery


Could someone please help me to add the command hide for all the other buttons, in that function. Because in this function I can put several buttons on the same page without having to deuterated the function.

var d = document;
function trclick(a){
  var b=a.id,view,valbt;
  var c=$("#bd_"+b);
  var e=d.getElementById('nod_'+b);
  view=c.css('display');
  c.toggle('slow');
  valbt=(view=='none'?'[-]':'[+]');
  e.innerHTML=valbt;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<center>
  <button id="look1" onclick="trclick(this);" style="font-size: 11px; cursor: pointer;"><span id="nod_look1">[+]</span>Look1</button>
  <div id="bd_look1" style="border: 0px inset; margin: 0px; padding: 6px; display: none;">
    HELLO
  </div><br />
  
  <button id="look2" onclick="trclick(this);" style="font-size: 11px; cursor: pointer;"><span id="nod_look2">[+]</span>Look2</button>
  <div id="bd_look2" style="border: 0px inset; margin: 0px; padding: 6px; display: none;">
    HELLO
  </div><br />
  
  <button id="look3" onclick="trclick(this);" style="font-size: 11px; cursor: pointer;"><span id="nod_look3">[+]</span>Look3</button>
  <div id="bd_look3" style="border: 0px inset; margin: 0px; padding: 6px; display: none;">
    HELLO
  </div>  
</center> 


Solution

  • Add a class (Ex: "bd") for the content divs and always hide them before showing the current one. The same for the [+] / [-] spans.

    var d = document;
    function trclick(a){
      var b=a.id,view,valbt;
      var c=$("#bd_"+b);
      $(".bd").hide(100); //hide all first
      $(".nod").html('[+]'); //reset labels to [+]
      c.toggle('slow'); //it could be c.show('slow')
      $("#nod_"+b).html('[-]'); //current label to [-]
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
    <center>
      <button id="look1" onclick="trclick(this);" style="font-size: 11px; cursor: pointer;"><span class="nod" id="nod_look1">[+]</span>Look1</button>
      <div id="bd_look1" class="bd" style="border: 0px inset; margin: 0px; padding: 6px; display: none;">
        HELLO
      </div><br />
      
      <button id="look2" onclick="trclick(this);" style="font-size: 11px; cursor: pointer;"><span class="nod" id="nod_look2">[+]</span>Look2</button>
      <div id="bd_look2" class="bd" style="border: 0px inset; margin: 0px; padding: 6px; display: none;">
        HELLO
      </div><br />
      
      <button id="look3" onclick="trclick(this);" style="font-size: 11px; cursor: pointer;"><span class="nod" id="nod_look3">[+]</span>Look3</button>
      <div id="bd_look3" class="bd" style="border: 0px inset; margin: 0px; padding: 6px; display: none;">
        HELLO
      </div>
    </center>