Matheno
Matheno

Reputation: 4142

How to hide div when it's already open?

I couldn't think of any better title, so I will try to explain my question here as clear as possible. I'm quite a newbie in JQuery so this is probably a very easy question.

I have some divs with a button on it. When you click the button, another div should pop-up. My question is: How can I make the div, which is already open, close when clicking on another button?

I made a fiddle with some example code: http://jsfiddle.net/zuvjx775/1/

And the example code here:

HTML:

<div class="wrapper">
    <div class="test">
        <input type='button' class='showDiv' id="1" value='click!' />    
    </div>
    <div class="show_1">

    </div>
</div>
<br>
<div class="wrapper">
    <div class="test">
        <input type='button' class='showDiv' id="2"value='click!' /> 
    </div>
    <div class="show_2">

    </div>
</div>

JQuery:

$('.showDiv').on('click', function(){
    var id = $(this).attr('id');
    $('.show_'+id).show();
});

When show_1 for example is visible, and I click on the button in div2, I want show_2 to come up, which it does, but show_1 to dissapear.

Can someone point me in the right direction?

Upvotes: 2

Views: 180

Answers (2)

MightyBarto
MightyBarto

Reputation: 21

Is the structure of the document fixed? is so... I guess the easiest way of doing this is to just do the following:

$('.showDiv').on('click', function(){
    var id = $(this).attr('id');
    if(id == 1){
      $('.show_1').show();
      $('.show_2').hide();
    }else{
      $('.show_2').show();
      $('.show_1').hide();
    }        
})

Upvotes: 1

Alex Char
Alex Char

Reputation: 33218

You can hide all divs that their class starts with 'show' before show the one you want. For example:

$('.showDiv').on('click', function() {
  var id = $(this).attr('id');
  $("div[class^='show']").hide();//find div class starts with 'show' and hide them
  $('.show_' + id).show();
});
.test {
  border: 1px solid black;
  height: 100px;
  width: 450px;
  float: left;
}
.show_1 {
  width: 50px;
  height: 50px;
  background-color: yellow;
  float: left;
  display: none;
}
.show_2 {
  width: 50px;
  height: 50px;
  background-color: green;
  float: left;
  display: none;
}
.wrapper {
  clear: both;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
  <div class="test">
    <input type='button' class='showDiv' id="1" value='click!' />
  </div>
  <div class="show_1">

  </div>
</div>
<br>
<div class="wrapper">
  <div class="test">
    <input type='button' class='showDiv' id="2" value='click!' />
  </div>
  <div class="show_2">

  </div>
</div>

Upvotes: 11

Related Questions