IAdapter
IAdapter

Reputation: 64717

How to simpify this javascript?

if (!errorHasHappened) {
    info.show();
    error.hide();
} else {
    info.hide();
    error.show();
}

I can't use toggle.

I tried to pass function show or hide to variable and then execute it, but it did not work for some reason and I got an JS error.

Upvotes: 0

Views: 150

Answers (5)

Java_User
Java_User

Reputation: 1321

Another way:

$( "#error" ).toggleClass( className, errorHasHappened);
$( "#info" ).toggleClass( className, errorHasHappened);

Upvotes: 1

Valdas
Valdas

Reputation: 1074

Anything that would make sense is to switch them around to prevent !

if (errorHasHappened) {
    info.hide();
    error.show();
} else {
    info.show();
    error.hide();
}

Upvotes: 1

techfoobar
techfoobar

Reputation: 66663

If making code shorter is your goal:

errorHasHappened?(info.hide(),error.show()):(info.show(),error.hide());

BTW, making code shorter !== simplifying code. IMO atleast..

Upvotes: 1

Cerbrus
Cerbrus

Reputation: 72837

You could try something like this:

info[errorHasHappened?'hide':'show']();
error[errorHasHappened?'show':'hide']();

But that's the only option that I can think of, that makes the code shorter.

Code like that doesn't make it easier to maintain, though.

Upvotes: 3

xdazz
xdazz

Reputation: 160833

You could do like this, but if statement is much clearer.

And why not use .toggle which is designed for such case?

info[errorHasHappened ? 'hide' : 'show']();
error[errorHasHappened ? 'show' : 'hide']();

Upvotes: 6

Related Questions