On second click; jQuery

<div class="example">


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.


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:


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');


Need Your Help

Python: Unexpected conditional activation in simple bisection search game

python bisection

I'm wrote some code to determine a secret number between 0 and 100. The user tells the machine the guessed number (which is half the range) is either to high, too low or just right. Based on the in...

Why should I both Unit test AND Web test (instead of just web test)?

c# asp.net visual-studio unit-testing

My current position is this: if I thoroughly test my ASP.NET applications using web tests (in my case via the VS.NET'08 test tools and WatiN, maybe) with code coverage and a broad spectrum of data, I