hellomello hellomello - 4 years ago 362
Javascript Question

jQuery toggleClass() between multiple classes

I would like to toggleClass between multiple elements:

<div class='container'>
<div class='main'>
<div class='par' id='1'></div>
<div class='par' id='2'></div>
<div class='par' id='3'></div>
<div class='par' id='4'></div>
</div>
</div>


I have this

$('.main').delegate('.par','click',function(){
$(this).toggleClass('media-clicked');
});


I understand that if i click the element say, #1, then it will add class media-clicked and if I click it again, it removes it. However, I'd like to click on #1, and then without clicking it again, click on another element say #4, it'll remove the other media-clicked (#1).

How would I do such a thing?

Thanks!

Answer Source

So essentially you want to move the class to a new element. I would advise using a "wrapper" element for reusability. In this case the div with main class is enough, this way you can look for any sibblings of the current element that have the class you want to remove, remove it, and add it to the current element, like so:

// you can use .on instead of .delegate if your jquery version is > 1.7
$('.main').delegate('.par','click',function(){
    $(this).sibblings(".media-clicked").removeClass("media-clicked");
    $(this).addClass('media-clicked');
});

This allows you to use other blocks with the same structure and still maintain the functionality separate on each block.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download