2
function changeButton () {
    if (event.currentTarget.className == 'btnRed') {
        event.currentTarget.className = 'btnGreen';
    } else {
        event.currentTarget.className = 'btnRed';
    }
}

Let's say I have the above code. I have seen similar codes written that would combine these two, but I don't really remember how it did it. It was something like className = (btnGreen | btnRed).
I am very sorry for the vagueness of this question.

0

1 Answer 1

4

You can use the ternary operator (condition) ? (true) : (false)

event.currentTarget.className = event.currentTarget.className == 'btnRed' ? 'btnGreen' : 'btnRed';

I would go a little bit further, extract the strings into variables to remove the ability to mistype them across the solution. And refactor event.currentTarget into a variable.

var RED_BUTTON_CLASS = 'btnRed', 
    GREEN_BUTTON_CLASS = 'btnGreen';

var currentTarget = event.currentTarget;

currentTarget.className = currentTarget.className == RED_BUTTON_CLASS ? GREEN_BUTTON_CLASS : RED_BUTTON_CLASS;

This I feel will just make it easier in the long run, completely optional

Edit

So adding extra information from what Jan said.

var RED_BUTTON_CLASS = 'btnRed', 
    GREEN_BUTTON_CLASS = 'btnGreen';

These probably describe a state, so you could better name them:

var ERROR_BUTTON_CLASS = 'btnRed', 
    OK_BUTTON_CLASS = 'btnGreen';
Sign up to request clarification or add additional context in comments.

2 Comments

And while you're at it, remove the references to "red" and "green" and instead describe their actions/states. "red" or "green" is likely to change in a redesign, "pressed", "hover" or "disabled" f.e are not.
It's ECMAScript name is the Conditional Operator ( ? : ), which is a ternary operator. ;-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.