Reputation: 337
I am trying to improve my coding skills, but I can not seem to figure this out. How do I write the following in shorthand?
/* fade */
$('.toggle-ui').on({
'click': function (e) {
e.preventDefault();
var divToFade = ['#logo', '#hide-interface'];
$.each(divToFade, function(intValue, currentElement) {
// check alpha state and switch
var currOp = $(currentElement).css('opacity');
if (currOp == 1) $(currentElement).css('opacity', 0.5);
if (currOp == 0.5) $(currentElement).css('opacity', 1);
});
}
Upvotes: 1
Views: 166
Reputation: 14465
Use the ternary operator:
$(currentElement).css('opacity', currOp == 1 ? 0.5 : 1);
As a side note: I am used to using ===
over ==
to avoid accidental mistakes by unintended type coercion. To use it here, I would parse currOp
to a number via +
:
$(currentElement).css('opacity', +currOp === 1 ? 0.5 : 1);
For more information, have a look here.
Upvotes: 7
Reputation: 25144
You can also do simple math:
$(currentElement).css('opacity', 1.5 - currOp);
Since
1.5 - 1.0 = 0.5
1.5 - 0.5 = 1.0
Upvotes: 2