Danny Danny - 3 months ago 8
CSS Question

Display div and hide another div by button press

I have two divs. I need 2 buttons, one for each of them. The first div is displayed but the second is hidden. When I press the second div's button, it will display and the first div will go hidden. Again, when I press the first div's button the first div will display and the second one will go hidden. I need the html and js code for those 2 buttons. Please help. :)

Answer

$('button').click(function(){    
  if(this.id == 'btn1'){
    $('.div1').show();
    $('.div2').hide();
  }else{
    $('.div1').hide();
    $('.div2').show();
  }
})
div{
  width: 200px;
  height: 200px;
  background: cornflowerblue;
  line-height: 200px;
  text-align: center;
  margin: 10px;
}

.div1{
  display: block;
  background: crimson;
}

.div2{
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="div1">
  DIV 1
</div>

<div class="div2">
  DIV 2
</div>

<button id="btn1">show Div 1</button>
<button id="btn2">show Div 2</button>

Comments