Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to make a show/hide toggle button with jquery

Hi I have been trying to make a show/hide toggle button with jquery but I can only find buttons that show a div but none that hide it

below is one of the examples I found that shows a div but it doesn't let you hide it unless you click on another button. I would like to be able to use the same button to show and hide a div. I have multiple divs on my page and would like to be able to use jquery instead of javascript.

<html>
 <head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
    $(document).ready(function(){

        $(".buttons").click(function () {
        var divname= this.value;
          $("#"+divname).show("slow").siblings().hide("slow");
        });

      });
</script> 
     </head>
        <body>


 <div id="buttonsDiv"> 

  <input type="button" id="button1" class="buttons" value="div1"></input>
  <input type="button" id="button2" class="buttons" value="div2"></input>
  <input type="button" id="button3" class="buttons" value="div3"></input>
  <input type="button" id="button4" class="buttons" value="div4"></input>

  </div>

   <div>

     <div id="div1" style="display:none">
    Hello World
     </div>

     <div id="div2" style="display:none">
       Test
   </div>

        <div id="div3" style="display:none">
          Another Test
  </div>

     <div id="div4" style="display:none">
     Final Test
     </div>


         </div>


     </body>
    </html>
like image 839
billy Avatar asked Feb 27 '26 05:02

billy


2 Answers

Try this

$(".buttons").click(function () {
  var divname= this.value;
  $("#"+divname).slideToggle().siblings().hide("slow");
});
like image 106
ShankarSangoli Avatar answered Mar 01 '26 18:03

ShankarSangoli


Even simpler use control's own toggle function.

$('.toggleButtons').click(function()
{
    $('control1, control2, ...').toggle();
});
like image 32
atoMerz Avatar answered Mar 01 '26 19:03

atoMerz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!