Search code examples
javascriptjqueryslidetoggle

jQuery manage many toggles


I need to use slideToggle() for too many divs to show and hide them.

This is my code, it doesn't work correctly:

$(".account-update").hide();
$(".account-update-pwd").hide();

$(".slide-toggle").click(function() {
    $(".account-update").slideToggle();
    $(".account").slideToggle();
});
$(".slide-toggle-pwd").click(function() {
    $(".account-update-pwd").slideToggle();
    $(".account-update").slideToggle();
});

HTML:

<a href="#" class="slide-toggle">Update Account</a>
<a href="#" class="slide-toggle-pwd">Change Password</a>

Solution

  • I have updated your code with a nice generic solution below.

    $(".account-update").hide();
    $(".account-update-pwd").hide();
    
    $("a.slide-toggle").click(function() {
      var targetDiv = $($(this).attr('data-selector'));
      var otherDivs = $("div.slide-toggle").not(targetDiv);
      
      otherDivs.each(function(){
        if($(this).is(':visible')) {
          $(this).slideToggle();
        }
      });
      
      targetDiv.slideToggle(function(){
        if($("div.slide-toggle:visible").length === 0) {
          $(targetDiv.attr('data-default')).slideToggle();
        }
      });
    });
    div {
      height: 100px;
    }
    
    .account {
      background-color: red;
      color: white;
    }
    
    .account-update {
      background-color: green;
      color: white;
    }
    
    .account-update-pwd {
      background-color: blue;
      color: white;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="slide-toggle account">Account Div</div>
    <p><a href="#" class="slide-toggle" data-selector=".account-update">Update Account</a></p>
    <div class="slide-toggle account-update" data-default=".account">Account Update Div</div>
    <p><a href="#" class="slide-toggle" data-selector=".account-update-pwd">Change Password</a></p>
    <div class="slide-toggle account-update-pwd" data-default=".account">Account Password Update Div</div>