How to write ternary operator condition in jQuery?

Viewed 133049

In this fiddle http://jsfiddle.net/mjmitche/6nar4/3/, if you drag, for example, the little blue box into the yellow box, then the big black box will turn pink. All of the 4 boxes along the left can be dragged into the boxes inside the black box.

At the end of the fiddle, you see the code that changes the black box to pink.

However, I want to make that a ternary operator, so that if the box is black, then it turns pink, but if it's been turned pink, then I want it to go back to black.

I know the ternary is like this

x ? y: z

So I tried this, even though I knew it wasn't probably right

$("#blackbox").css({'background':'pink'}); ?

    $("#blackbox").css({'background':'black'}); : 

$("#blackbox").css({'background':'pink'}); 

I think the first line before the question mark is causing the problem, so how to create the if statement?

9 Answers

Here is a working example in side a function:

function setCurrency(){
   var returnCurrent;
   $("#RequestCurrencyType").is(":checked") === true ? returnCurrent = 'Dollar': returnCurrent = 'Euro';
   
   return returnCurrent;
}

In your case. Change the selector and the return values

$("#blackbox").css('background-color') === 'pink' ? return "black" : return "pink";

lastly, to know what is the value used by the browser run the following in the console:

$("#blackbox").css('background-color')

and use the "rgb(xxx.xxx.xxx)" value instead of the Hex for the color selection.

Related