DinoMyte
DinoMyte

Reputation: 8868

ToggleClass doesn't work

I recently experienced a scenario where the toggleClass doesn't work if the css class you are toggling to appears before the class currently assigned to the element.

Here's the code :

<button id="btn1" class="red">This works</button>
<button id="btn2" class="yellow">This doesn't work</button>

<script>
      $('#btn1').click(function(){
          $(this).toggleClass('yellow'); 
       });

        $('#btn2').click(function(){
           $(this).toggleClass('red');
       });
</script>

<style>
.red { color:red }
.yellow { color: yellow }
</style>

Fiddle : http://jsfiddle.net/x39zu3nf/2/

As you can see from the code posted on the above fiddle, toggleClass works on one button but doesn't work on the other one.

Could anybody tell me why its behaving differently ?

Upvotes: 0

Views: 324

Answers (4)

Roman Romanovsky
Roman Romanovsky

Reputation: 578

It works, and when you click you get :

<button id="btn1" class="red yellow">This works</button>

<button id="btn2" class="yellow red">This doesn't work</button>

But priority of css selector shows yellow color. But you can do like this https://jsfiddle.net/x39zu3nf/6/

Upvotes: 1

Andrew Brooke
Andrew Brooke

Reputation: 12173

.yellow is declared later in the CSS, so it has priority over .red for color

You can use this:

$('#btn1').click(function(){
    $(this).toggleClass('yellow red');
});

$('#btn2').click(function(){
    $(this).toggleClass('yellow red');
});

Upvotes: 2

Gab
Gab

Reputation: 5784

It actually does work but the yellow class is defined after the red class so it has priority over it.

When you hit the btn 1, it get both class="yellow red".

When you hit the btn 2, it get both class="red yellow".

A good way to solve this elegantly could be using a base class and a color class like this fiddle

CSS

.base { color:red }
.yellow { color: yellow }

HTML

<button id="btn1" class="base">This works</button>
<button id="btn2" class="base yellow">Works also</button>

JS

function toggleYellow(){
    $(this).toggleClass('yellow');
}

$('#btn1').click(toggleYellow);
$('#btn2').click(toggleYellow);

Upvotes: 3

Reza Mansouri
Reza Mansouri

Reputation: 158

change the second button code to this:

$(this).toggleClass('red').toggleClass('yellow');

Upvotes: 1

Related Questions