Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple show/hide divs with separate toggle

I have been trying to create multiple divs which should be hidden at page load. The div should be shown if the corresponding button is clicked and should hide if the same button is clicked again. Also if one of the divs is being shown and another button is clicked, then the div corresponding to that button should show up. If the same button is clicked again then the div should hide. I have followed a thread on SO for the same and am able to show divs corresponding to button click but the toggle functionality is not working.

Please find the fiddle :

jQuery(function() {
  jQuery('.showSingle').click(function() {
    jQuery('.targetDiv').hide();
    jQuery('#div' + $(this).attr('target')).show();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="buttons">
  <a class="showSingle" target="1">Div 1</a>
  <a class="showSingle" target="2">Div 2</a>
  <a class="showSingle" target="3">Div 3</a>
  <a class="showSingle" target="4">Div 4</a>
</div>

<div id="div1" class="targetDiv">Lorum Ipsum1</div>
<div id="div2" class="targetDiv">Lorum Ipsum2</div>
<div id="div3" class="targetDiv">Lorum Ipsum3</div>
<div id="div4" class="targetDiv">Lorum Ipsum4</div>

https://jsfiddle.net/8pyovyqn/3/

Any help is appreciated.

like image 880
Pravin Avatar asked Jun 16 '26 19:06

Pravin


1 Answers

Use not to hide the all except clicked one and set style="display:none;" for all the div to hide them by default.

$(function() {
  $('.showSingle').click(function() {
    $('.targetDiv').not('#div' + $(this).attr('target')).hide();
    $('#div' + $(this).attr('target')).toggle();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="buttons">
  <a class="showSingle" target="1">Div 1</a>
  <a class="showSingle" target="2">Div 2</a>
  <a class="showSingle" target="3">Div 3</a>
  <a class="showSingle" target="4">Div 4</a>
</div>

<div id="div1" class="targetDiv" style="display:none;">Lorum Ipsum1</div>
<div id="div2" class="targetDiv" style="display:none;">Lorum Ipsum2</div>
<div id="div3" class="targetDiv" style="display:none;">Lorum Ipsum3</div>
<div id="div4" class="targetDiv" style="display:none;">Lorum Ipsum4</div>
like image 53
Kiran Shahi Avatar answered Jun 18 '26 07:06

Kiran Shahi



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!