Benjamin Karami
Benjamin Karami

Reputation: 155

switch between 2 div's

I want to switch between 2 div's so that when I click on one of them its border and header became red and I want the other div goes off. so its be like a choice between them I don't know where I'm doing it wrong I add (IF) so I can make it happen but it is not working pls help me.

$(".container").on("click" , function(){    
  $(this).toggleClass("active");
  $(".header", this).toggleClass("active2");    
  if ($(".box1").hasClass("active")) {       
    $(".box2").removeClass("active");
    $("h2", ".box2").removeClass("active2");    
  }if ($(".box2").hasClass("active")) {       				
    $(".box1").removeClass("active");
    $("h2", ".box1").removeClass("active2");    
  }        
});
body{
  padding: 3em;
}
.box1, .box2{
  padding: 2em;
  border: 1px solid silver;
  margin-top: 2em;
}    
.active{
  border-color: red;
}    
.active2{
  color: red;
}    
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container box1">
  <h2 class="header">Boys</h2>
  <hr>
  <p>Benjamin</p>
  <p>David</p>
</div>    
<div class="container box2">
  <h2 class="header">Girls</h2>
  <hr>
  <p>Sara</p>
  <p>Tania</p>
</div>

Upvotes: 1

Views: 50

Answers (1)

Mohammad
Mohammad

Reputation: 21489

You don't need to many code to do this work. Add .active to clicked element and remove class from sibling of it.

$(".container").on("click", function() {
  $(this).toggleClass("active").siblings().removeClass("active");
});
body{padding: 3em}
.box1, .box2{
  padding: 2em;
  border: 1px solid silver;
  margin-top: 2em;
}    
.active {border-color: red}    
.active .header{color: red}    
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container box1">
  <h2 class="header">Boys</h2>
  <hr>
  <p>Benjamin</p>
  <p>David</p>
</div>    
<div class="container box2">
  <h2 class="header">Girls</h2>
  <hr>
  <p>Sara</p>
  <p>Tania</p>
</div>

Upvotes: 3

Related Questions