user1355300
user1355300

Reputation: 4987

on click, add class to alternative div with jQuery

I have two divs, div1 and div2. On clicking any of these div, I want to remove class .active from it and add that class to the other div.

I'm trying following code, but I cant figure out how to add the class to the other div which is not clicked. Thanks.

$('.div').click(function() {
  $(".div").removeClass("active");
});
.div1 {
  background: green;
  display: none;
}
.div2 {
  background: red;
  display: none;
}
.active {
  display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="div div1 active">div1</div>
<div class="div div2">div2</div>

Fiddle http://jsfiddle.net/vLLtLwxy/

Upvotes: 1

Views: 2093

Answers (4)

mjwunderlich
mjwunderlich

Reputation: 1035

Here's another way of highlighting the next (adjacent) element of the one clicked on:

$('div').click(function() {
    $('div:active').removeClass('active');
    var next = $(this).next();
    if (0 == next.length) {
        next = $('div:first');
    }
    $(next).addClass('active');
});

Cycle between 7 divs: http://jsfiddle.net/k0oq4hd5/1/

Cycle between 3 divs: http://jsfiddle.net/k0oq4hd5/2/

Upvotes: 1

Tui Popenoe
Tui Popenoe

Reputation: 2114

Use the .addClass method (MDN Docs):

<div id="div1" class="div active">div1</div>
<div id="div2"class="div">div2</div>

 $('.div').click(function(){
    $("#div1").removeClass("active");
    $("#div2").addClass("active");                    
});

Using ID selectors instead of class selectors ensures if you add more <div> elements they are not toggled like if you used .toggleClass

Upvotes: 0

Satwik Nadkarny
Satwik Nadkarny

Reputation: 5135

Just use toggleClass on both the div's as follows :

$(function () {    
     $('.div').click(function(){
        $(".div").toggleClass("active");
    });
});

See the snippet below :

$(function () {    
     $('.div').click(function(){
        $(".div").toggleClass("active");
    });
});
.div1{
    background: green;
    display: none;
}

.div2{
    background: red;
    display: none; 
}

.active{
    display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<div class="div div1 active">I'm div1</div>
<div class="div div2">I'm div2</div>

Hope this helps!!!

Upvotes: 1

Josh Crozier
Josh Crozier

Reputation: 241078

Since there are only two elements, you could just use .toggleClass().

Updated Example

$('.div').click(function(){
    $(".div").toggleClass("active");                     
});

Similarly, it's worth pointing out that you could also negate one of the elements using .not():

Example Here

$('.div').click(function(){
    $(this).removeClass("active");
    $('.div').not(this).addClass('active');
});

Upvotes: 4

Related Questions