HiveBrain v1.2.0
Get Started
← Back to all entries
patternhtmlMinor

Changing color on button click

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
changingclickcolorbutton

Problem

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


    Button Fun
    
    
    
    
    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;
            }   
        });
    });
    

    Press


CSS

button{
    background-color: blue;
    height:100px;
    width:150px;
}

Solution

$("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;
});

Code Snippets

$("button").click(function(){
    if(clicked){
        $(this).css('background-color', 'red');
        clicked  = false;
    } else {
        $(this).css('background-color', 'blue');
        clicked  = true;
    }   
});
$("button").click(function(){
    var color = clicked ? 'red' : 'blue';
    $(this).css('background-color', color);
    clicked = !clicked;
});
$("button").click(
    $(this).css('background-color', isButtonBlue ? 'red' : 'blue');
    isButtonBlue = !isButtonBlue;
});

Context

StackExchange Code Review Q#134106, answer score: 9

Revisions (0)

No revisions yet.