jquery - slide toggle div code which close when clicked again -


i'm still relatively new jquery, i'm using below code, , works want: show multiple content in same container have 1 active @ time , hides rest.

however want so: if click same button again content that's active, closes content again content hidden. can't work.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="buttons">     <a href="#" class="links" data-showdiv="content1" id="button1">button 1</a>     <a href="#" class="links" data-showdiv="content2" id="button2">button 2</a>     <a href="#" class="links" data-showdiv="content3" id="button3">button 3</a> </div> <div id="container">     <div class="divs" id="content1" style="display:none">         test content 1     </div>     <div class="divs" id="content2" style="display:none">         test content 2     </div>     <div class="divs" id="content3" style="display:none">         test content 3     </div> </div> 
$(document).ready(function() {      $(".links").click(function () {         $(".divs:visible").slidetoggle();         $("#" + $(this).attr("data-showdiv")).slidetoggle();     }); });  

you need change logic first check if target div visible. try this:

$(".links").click(function () {     var $target = $("#" + $(this).data('showdiv'));     if ($target.is(':visible')) {         $(".divs:visible").slidetoggle();     } else {         $target.slidedown().siblings().slideup();     } }); 

example fiddle


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -