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)
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)
Share Improve this question edited Aug 5, 2013 at 19:19 Meredith asked Jul 2, 2013 at 4:03 MeredithMeredith 4,4545 gold badges36 silver badges58 bronze badges 1 |2 Answers
Reset to default 21You 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()
jQuery has a method that does what you want called toggle()
:
$('.perspective-col').toggle(b);
$.fn[b ? "show" : "hide"].call($(".perspective-col"))
– Ian Commented Jul 2, 2013 at 4:21