Tuesday, December 23, 2008

Using ternary to choose between two methods in javascript

I found this little gem while looking at the jQuery source. I'd forgotten that you can reference properties/methods using obj["str"]. Pretty cool tip for getting your code smaller. Plus I like ternaries.

Before:
if($(this).hasClass("myClass")){
 $(this).hide();
}else{
 $(this).show();
}
After:
$(this)[$(this).hasClass("myClass")?"hide":"show"]();

This is doubly useful if you got a big chain in jQuery and don't want to break it for the if statement.

Edit(2009-3-1): As of jQuery 1.3 there's is now an optional parameter for toggle(), toggleClass(), slideToggle(), fadeToggle(). It's a bool that sets the toggle state. So now the previous statement can be written like this as well:

$(this).toggle(!$(this).hasClass("myclass"));