user188962
user188962

Reputation:

Is it really not possible to add actions to this shortened if statement in js?

(category=="Villor/Radhus mm")?byId("nav_sub_villor").style.display='block' :  byId("nav_sub_villor").style.display='none';

I would like to call a function if the statement above is true...

But it doesn't seem possible...

Just want to be sure it is not possible, does anybody know?

Upvotes: 0

Views: 88

Answers (4)

naivists
naivists

Reputation: 33531

It is possible. You can wrap your code inside an anonymous function and immediately call it. For instance, this one first alerts I'm in a function and then alerts 1

var i=1;
var a =  (i==1) ? (function(){alert("I'm in a function"); return 1})() : (function(){return 2})();
alert(a);

EDIT: Sorry, this is named self-invoking function, see here: http://www.hunlock.com/blogs/Functional_Javascript

Upvotes: 1

Plutor
Plutor

Reputation: 2897

Why would you want to shorten an if statement in that way? You're just going to give headaches to the next person to come along and maintain it.

if (category=="Villor/Radhus mm")
    byId("nav_sub_villor").style.display='block';
else
    byId("nav_sub_villor").style.display='none';

Upvotes: 0

Yuval Adam
Yuval Adam

Reputation: 165312

Sure you can:

function doIfTrue()
{
    byId("nav_sub_villor").style.display='block';
    // call other function
}

function doIfFalse()
{
    byId("nav_sub_villor").style.display='none';
}

(category=="Villor/Radhus mm") ? doIfTrue() : doIfFalse();

Note that an expression something like condition ? statement; statement : statement; is illegal in JS.

However if you really need to keep it a one-liner, you can push it all into an anonymous function:

(category=="Villor/Radhus mm") ? function() { byId("nav_sub_villor").style.display='block'; doOtherStuff();}() :  byId("nav_sub_villor").style.display='none';

Upvotes: 3

Ryan Joy
Ryan Joy

Reputation: 3039

You can have multiple statements or function calls in this ternary statement. To call another function if true, just add it before or after the first section where you set the display to 'block'.

Upvotes: 0

Related Questions