UserIsCorrupt UserIsCorrupt - 1 year ago 45
jQuery Question

On second click; jQuery

<div class="example">


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

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

Answer Source

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