Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Hide/Show if conditional statement

Tags:

jquery

dom

I do this a lot:

var condition = true;
if (condition === true) {
    $('#condition_dependancy').show();
} else {
    $('#condition_dependancy').hide();
}

Can this be any cleaner syntactically? I could write my own:

$('#condition_dependancy').hidden(condition);

But i'm just wondering if there is anything built in.

like image 202
Dom Vinyard Avatar asked Dec 12 '13 10:12

Dom Vinyard


2 Answers

You can use toggle:

var condition = true;
$('#condition_dependancy').toggle(condition);

Side note: Don't use things like

if (condition === true)

unless there's a possibility that condition will have a different "truthy"* value and you only want the expression to be true if it's precisely true and not if it's just truthy. In general == (boolean) and (in JavaScript) === (boolean) is just noise (although in JavaScript there are edge cases for using the === version).

Prefer:

if (condition)

and (for the == false / === false case):

if (!condition)

* "truthy": In JavaScript, types can be coerced by expressions. Anywhere a boolean is expected, if you use something that isn't a boolean, it's coerced into being one. Things that coerce to true are called "truthy" values; things that coerce to false are called "falsey" values. The falsey values are 0, "", NaN, undefined, null, and of course, false. Everything else is truthy.

like image 82
T.J. Crowder Avatar answered Nov 03 '22 19:11

T.J. Crowder


Using toggle():

$('#condition_dependancy').toggle(condition);
like image 45
A. Wolff Avatar answered Nov 03 '22 21:11

A. Wolff