开发者

JS slideToggle close other open divs

I have about 20 buttons on a page. I have set them up with jquery to slide toggle to show and hide a div. It works well but only if the same button is used to close the div before selecting a new div. I want that if a button is clicked it will slide up open divs, before it slides down its own div. Right now if a div is still showing, and a different button is clicked, the open div wont close.

I think there are too many buttons to make an if function to test each div by name if open, and then slide up. is there a general slide up all open divs?

If I add a class and use css to di开发者_运维知识库splay:block, I dont get animation, so I am using slidetoggle. I am happy to redo my code if there is a better way? Is there a way to close the open divs?

$(document).ready(function(){
  $('.show1').click(function(){
    $(".row1").slideToggle();
  });

  $('.show2').click(function(){
    $(".row2").slideToggle();
  });

  $('.show3').click(function(){
   $(".row3").slideToggle();
  });
});


The easiest way I see is to add a class (like row) to all your div and to hide them using $(".row").not(".rowX").slideUp(); The not rowX is there to keep the toggle alive (and with that update, order doesn't matter ;)).

That'll end up like:

$('.show3').click(function(){
   $(".row").not(".row3").slideUp();
   $(".row3").slideToggle();
});


The simplest way to do this is to check whether or not the other divs are displaying and if they are, close them. I only show 2 divs below, but you can make an array of the divs and loop through it for all of them.

This has all divs closed and then when one opens, the rest toggle close each time one is clicked.

$("#div1").hide();
$("#div2").hide();

$("#div1Button").click(function () {
   $("#div1").slideToggle();

   if ($("#div2")[0].style.display != "none") {
       $("#div2").slideToggle();
   }
})

$("#div2Button").click(function () {
    $("#div2").slideToggle();

    if ($("#div1")[0].style.display != "none") {
        $("#div1").slideToggle();
    }
})
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜