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.

4 comments:

Unknown said...

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

Syntrino said...

Thank you so much for this amazing posts and please keep update like this excellent article.thank you for sharing such a great blog with us. expecting for your.
Software Development Service Company in Malaysia
Best Api Integration Development
Company Malaysia

Wikisol Web Design & SEO Company said...

It is a very nice blog. Really it is a very international destination post. Thanks for sharing this post.
iOS Apps Development Company Islamabad

Mr Rahman said...

Really Helpful Article & Thanks for sharing.
Oflox Is The Best Website Design & Development Company In Dehradun