jQuery: The Write Less, Do More JavaScript Library

Re: show/hide/toggle: suggestion to reduce show/hide code

by Hector Virgen :: Rate this Message:

Reply to Author | View in Thread

I ran into this same problem today and wrote up this quick plugin that accepts a boolean or function:

$.fn.extend({
showIf: function(fn)
{
var result;
switch (typeof fn) {
case 'function':
result = fn.call(this);
break;
default:
result = fn;
}
if (result) {
$(this.show());
} else {
$(this.hide());
}
return $(this);
}
});


Usage example:

// Show all LI's based on value of condition
var condition = true;
$('ul.tabs li').showIf(condition);

// Show all LI's that contain exactly 3 anchors
$('ul.tabs li').showIf(function()
{
    return ($(this).find('a').length == 3);
});

I hope this helps :)


-Hector


On Tue, Nov 18, 2008 at 11:13 PM, Dylan Verheul <dylan.verheul@...> wrote:

On Tue, Nov 18, 2008 at 19:58, Karl Swedberg <karl@...> wrote:
> On Nov 18, 2008, at 9:02 AM, Dylan Verheul wrote:
> Hmm, I actually checked the docs for that because that would make
> .toggle an unsuitable overloader. The docs said toggle doesn't take
> arguments:
>
> Hmmm, indeed. :) Not so much outdated as incomplete. I just went ahead and
> added it to the docs:
> http://docs.jquery.com/Effects/toggle#speedcallback

Good :-) Anyway, that means no simple overloading method is available.
Of course it's no problem to code it or even to write a plugin, but I
thought overloading an existing function would make for an interesting
and probably often-used functionality, which was the point of starting
this thread.

 « Return to Thread: show/hide/toggle: suggestion to reduce show/hide code