Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript ternary operators for method calls

I would like to be able to do this:

var b = $(this).is(':checked')
$('.perspective-col'). (b) ? show() : hide()

instead of

var b = $(this).is(':checked')
if(b) {    
    $('.perspective-col').show() 
} else {
    $('.perspective-col').hide()
}

Am I wishing for too much? Or is there some wonderful javascript syntax I haven't found yet? Or am I right in thinking that no such thing exists in JQuery thus far? (I'm using JQuery 1.9.0)

like image 910
Meredith Avatar asked Nov 28 '22 17:11

Meredith


1 Answers

You can use this :

var b = $(this).is(':checked')
$('.perspective-col')[b ? 'show' : 'hide']()

You can call jQuery function by passing a string into the bracket []. Just insert a condition inside to decide which string you pass!

In general,

<any expression>.property

is equivalent to:

<any expression>['property']

The difference is that you can replace the literal 'property' in the brackets with an expression that calculates the property name. jQuery methods are just properties whose values happen to be functions.

But I actually hate that practice. You can also use jQuery .toggle()

like image 147
Karl-André Gagnon Avatar answered Dec 05 '22 02:12

Karl-André Gagnon