UserIsCorrupt UserIsCorrupt - 5 months ago 17
jQuery Question

On second click; jQuery

<div class="example">
Test
</div>

$('.example').click(function(){
$(this).css('color','red');
});


When the code above get's clicked, it will apply the
.css
. Now what I need is for another bit of code (let's say
$(this).css('color','blue');
) to be applied, replacing the previous code when
.example
gets clicked a second time.

I've searched for this and askers seem to only need
.show
/
.hide
events which can be substituted with
.toggle
, which is obviously not the case here.

Answer

Since you may have many instances of class example, simply maintaining a state using a single variable is not feasible, what you can do is to maintain the state of each instance of example within itself:

Define two css classes

.example { background:blue }
.example.red { background:red }

Then your click method:

$('.example').click(function(){
 $(this).toggleClass('red');
});

If you prefer not to define new css classes, you can use data(), to make sure that the state is exclusive within each .example, this is useful if you have many instances of .example

$('.example').click(function() {
    var color = $(this).data('color');
    if(color != 'blue') {
       $(this).css('color', 'blue');
       $(this).data('color', 'blue');
    } else {
       $(this).css('color', 'red');
       $(this).data('color', 'red');
    }
});

http://api.jquery.com/data/