Changing color on button click I have an html button that when the user clicks the button it will change color from blue to red and back.  Is there a better way to do this in jQuery?  

HTML/jQuery

&lt;html&gt;
&lt;head&gt;
    &lt;title&gt;Button Fun&lt;/title&gt;
    &lt;script src = 'bower_components/jquery/dist/jquery.js'&gt;&lt;/script&gt;
    &lt;script type="home.js"&gt;&lt;/script&gt;
    &lt;link rel="stylesheet" type="text/css" href="styles.css"/&gt;
    &lt;script type="text/javascript"&gt;
    clicked = true;
    $(document).ready(function(){
        $("button").click(function(){
            if(clicked){
                $(this).css('background-color', 'red');
                clicked  = false;
            } else {
                $(this).css('background-color', 'blue');
                clicked  = true;
            }   
        });
    });
    &lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;

    &lt;button&gt;Press&lt;/button&gt;

&lt;/body&gt;
&lt;/html&gt;


CSS

button{
    background-color: blue;
    height:100px;
    width:150px;
}
$("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. If 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;
});