There will be times where you wnat to toggle back and forth between two actions with the jQuery .click() method.

The .toggle() method seems like it should be the answer, but is not. The .toggle() method toggles between .show() and .hide() and relies on a separate element for the click so that it does not disappear.

You can use the .click() method, but you want to do is keep track of which state the element is so the next click does the opposite thing. One way is to create a Boolean global variable out side of the function that changes each time the element is clicked. The process that is run will be contained in an if(){}else{} statement that tests the state of the Boolean variable.

Of course there are many situations where this technique could be applied besides just with the .click() method. 

 

We will use a simple example of making the element turn red or green, depending on the state.

var flag = false;  // declare the testing variable outside the function
$("#stopLight").click(function(){
    flag = !flag; // this changes the variable from true to false or from false to true
    if (flag) {
        $(this).css("backgroundColor", "#990000");
        $(this).find("h2").html("STOP");
    } else {
        $(this).css("backgroundColor", "#449900");
        $(this).find("h2").html("GO");
    }
});

Test the result of this function below: