$("button").click(function(){ if(clicked){ $(this).css('background-color', 'red'); clicked = false; } else { $(this).css('background-color', 'blue'); clicked = true; } });
You could do it like this instead
$("button").click(function(){
var color = clicked ? 'red' : 'blue';
$(this).css('background-color', color);
clicked = !clicked;
});
We move the color picking to a single variable choice using a ternary statement and then we only have to write out the change to the CSS of the element once. then we flip the boolean.
I don't like the name of the boolean variable, it doesn't accurately describe what it is keeping track of, based on the way the code is written it should be named isButtonBlue.
If the button is blue, turn it red. ifIf the button is not blue, turn it blue.
After looking at this a little bit longer I was thinking that you could make it one line shorter by making another line longer by moving the ternary statement into the CSS change
$("button").click(
$(this).css('background-color', isButtonBlue ? 'red' : 'blue');
isButtonBlue = !isButtonBlue;
});