agon024 agon024 - 3 months ago 16
CSS Question

jQuery - Toggle class on $(this) and remove class on all others

Here is my jQuery snippet that I am using:

$('.panel-title').click(function(){
$(this).find('.state').toggleClass('rotate');
});


UPDATE - Edit the fiddle to match more what I am dealing with

Here is a fiddle showing you what I am talking about

https://jsfiddle.net/ke1hwn7f/9/

What I need to be able to do is toggle a class back and forth. That is pretty straight foward. But I also need to set it so that if that class already exists on an element I need to remove it.

So in the fiddle you can see that when you click "This is heading 4" it toggles the "colorChange" class. But then you click "This is heading 2" I need it to toggle that one green but also remove the class from "This is heading 4" (or anywhere else that it might exist) hopefully before it toggles the element that was just clicked.

Is there a way for me to do that?

Answer

There you go:

$('.panel-title').click(function(){
  if ($(this).find('.state').hasClass('rotate')){
    $('.panel-title').find('.state').removeClass('rotate');
  }
  else {
    $('.panel-title').find('.state').removeClass('rotate');
    $(this).find('.state').addClass('rotate');
  }
});

If it has the class, remove it to every title, else, remove it to all but add it to the one you clicked after.