Saturday, January 2, 2010

jQuery toggle

I recently found myself in a discussion about the best way to do a toggle link. Im not saying the problem is hard, but how do you solve it nicely? Since we all hate ifs ( 2 links on why: here and here )

In jQuery there is a nice way to handle this via the toggle method. Like this:

$("#the-link").toggle(function(){
$(this).text("Show");
// hide a list of related items to
$(this).parents(".my-list").find("li").hide();
}, function(){
$(this).text("Hide");
$(this).parents(".my-list").find("li").show();
});

This means if you click the link the text will be 'show' and all the list items will be hidden. The second time you click it the text will switch to 'hide' and the list items will be shown. According to the specs the toggle function could take any number of functions, which would allow you to do something crazy like:

$("#the-link").toggle(
function(){ ... },
function(){ ... },
function(){ ... },
function(){ ... }
);

Or why not:

function f() { ... };
function g() { ... };
function h() { ... };

$("#the-link").toggle(f,g,h,g,f,h,h,g,g);

But if the toggle-function is given no arguments it will toggles the visibility of the matched element. The pattern where a function behaves differently depending on the number of arguments its given is fairly typical to jQuery. For example: click() that triggers the click-event and click(function(){}) that listens for the click-event.

1 comment:

John Conner said...

Really good post thanks for sharing which is useful for me in the future.
Software Company Malaysia