On Nov 18, 2008, at 1:10 AM, Dylan Verheul wrote:
I'm building a new version of an often used data entry form on our
site Waarneming.nl (int'l version Observado.org).
It struck me that I often have to write something like this:
if (cond) $(this).show() else $(this).hide();
Since jQuery is about reducing and chaining, wouldn't it be nice if I
could write it like this:
$(this).toggle(cond); // shows if cond evaluates to true, else hides
Of course a new function showhide could be made for this, but toggle
seems a likely candidate for overloading.
Hey Dylan,
Of course, you could write it this way, too:
$(this)[cond ? 'show' : 'hide']();
But I grant you that it's still not as elegant as an overloaded
method. Not sure if toggle(cond) is the best choice, though. It's
already pretty overloaded as it is, and it can already take a string
or numeric argument for speed (e.g. 'slow'), which means you'd have to
make sure that cond === true, not just cond == true.
Maybe a simple plugin would be more appropriate here. Something like
this ...
(function($) {
$.fn.toggleIf = function(cond) {
return this.each(function() {
$(this)[cond ? 'show' : 'hide']();
});
};
})(jQuery);
--Karl
____________
Karl Swedberg
www.englishrules.com
www.learningjquery.com