2
votes

I use this script multiple times to hide some text:

$(document).ready(function(){
  $("#button_to_click_to_toggle").click(function(){
    $("#hidden_div").slideToggle("medium");
  });
});

I want to make it impossible to toggle two hidden divs at once.

Example:

Click on one button (#button1) = the hidden div (#div1) associated to that button shows.

Click another button (#button2) = The div (#div2) associated to that button shows and at the same time #div1 closes (slide to close).

Click another button (#button3) = The div (#div3) associated to that button shows and at the same time #div2 closes (slide to close).

2
What about using a jQuery UI accordion? jqueryui.com/accordion - LarsH

2 Answers

1
votes

Add a class .button to all of the buttons and .div to all divs. Then it's just a matter of:

$(".button").on('click', function () {
  var id = this.id.replace('button', '');

  //properly toggle visibility of selected div
  if ($("#div" + id).is(":visible")) {
     $("#div" + id).slideUp();
  }
  else {
    $("#div" + id).slideDown();
  }
   //hide all divs except the selected one
   $(".div").not("#div" + id).slideUp();
});

http://jsfiddle.net/6Lhxm/

0
votes

Could also hide all the divs on click and then show only the associated one:

javascript:

$(document).ready(function () {
  $("button").click(function () {
    $("div").hide();
    $(this).next().show();
  });
});

html:

<button type="button">one</button>
<div id="one">one</div>
<button type="button">two</button>
<div id="two">two</div>
<button type="button">three</button>
<div id="three">three</div>

http://jsfiddle.net/x7Ehq/