pab
pab

Reputation: 973

jQuery hide and show collapse multiple divs

I need to be able to hide and show divs on a page.

I need one active by default then when I click on other links to show another div, I need the active div to hide, and so on. So only one div is open at one given time.

I have put a demo together to show what I require, I have got it working so to speak, but I need it to collapse/hide the active div once another link is clicked.

http://jsfiddle.net/QFfzs/3/

Upvotes: 0

Views: 12685

Answers (3)

gaurang171
gaurang171

Reputation: 9080

Here i have done complete bin for above issue. you can check demo link....

Demo: http://codebins.com/bin/4ldqp84

HTML

<div id="panel">
  <a href="#">
    Show Default
  </a>
  <div class="box">
    <p>
      Default Div Box is already Active..!
    </p>
  </div>
  <a href="#">
    Show Box1
  </a>
  <div class="box">
    <p>
      Showing Div Box 1..!
    </p>
  </div>

  <a href="#">
    Show Box2
  </a>
  <div class="box">
    <p>
      Showing Div Box 2..!
    </p>
  </div>
  <a href="#">
    Show Box3
  </a>
  <div class="box">
    <p>
      Showing Div Box 3..!
    </p>
  </div>
  <a href="#">
    Show Box4
  </a>
  <div class="box">
    <p>
      Showing Div Box 4..!
    </p>
  </div>
</div>

CSS

.box{
  border:1px solid #334478;
  width:400px;
  height:50px;
  background:#f7a8a5;
  margin-top:3px;
  /* Default All Divs Are Hidden*/
  display:none;
}
#panel a{
  display:block;
  font-size:13px;
}
.box p{
  text-align:center;
}

jQuery

$(function() {
    //Show Default First div is Active
    $("#panel .box:first").show();
    $("#panel a").click(function() {
        $("#panel .box").hide(400);
        $(this).next(".box").show("slow");
    });
});

Demo: http://codebins.com/bin/4ldqp84

Upvotes: 0

CKKiller
CKKiller

Reputation: 1422

You need to add a class to the divs you're trying to hide, then hide the all divs before toggling like this:

//adding '.hideMe' to the divs to be toggled
$(document).ready(function() {
    $('#hideDetailsDiv').hide();
    $('a#hideDetailsButton').click(function() {
        if (!$('#hideDetailsDiv').is(':visible')) {
            $('.hideMe').hide(400);
        }
        $('#hideDetailsDiv').toggle(400);
    });
});

JSFiddle: http://jsfiddle.net/QFfzs/4/

Updated JSFiddle: http://jsfiddle.net/QFfzs/5/ (done with less code)

Upvotes: 4

user1440167
user1440167

Reputation: 1963

Try something like this :

$('.primaryButton2').click(function(){
   $('.hideDetailsDiv').hide();//hide all divs, add to them class .hideDetailsDiv
   $(this).nextAll('.hideDetailsDiv:first').show(400);
})

Upvotes: 1

Related Questions