Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Help me optimize the if else in JavaScript (jQuery)

Is it possible to somehow shorten this code:

var i=GetStringFromServer('/url');
if(i){
   $('#Div1').hide();
   $('#Div2').show();
}
else{
   $('#Div1).show();
   $('#Div2).hide();
}

In C# I'd simply do this:

bool smth=GetBool();
_el1.Visible=smth;
_el2.Visible=!smth;

Is it possible to mimick the logic in JavaScript?

UPDATE: Thank you guys for nice answers, I peeked at toggle myself before asking but what confused was the method signature:

toggle(fn1, fn2);

I thought that function expected some tricky callbacks but apparently it's flexible enough to handle both plain booleans and callbacks.

UPDATE2: Thanks to Robert's and Fabien's comments, the true answer was finally found. Toggle will always make elements visible or invisible based on evaluating the argument to bool.

like image 763
Valentin V Avatar asked Nov 18 '25 20:11

Valentin V


1 Answers

$('#Div1, #Div2').toggle(i);
like image 115
Darin Dimitrov Avatar answered Nov 20 '25 11:11

Darin Dimitrov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!