jquery use of toggle function


Using jQuery’s toggle() function

{ 14th Mar 2010 ~ 2 responses }



jQuery is packed full of useful features that help you to “write less, do more” as their slogan says. One thing I have found over the years, when working with JavaScript, is the need to know what state an object is in. By that I mean wanting for instance to know whether an information box is open or closed, and then perform an action based upon the answer to that question. Now in the past I would use variables to give me this information, and then alter their values based upon the actions taken by the user. This method is somewhat cumbersome and I don’t particularly like using it because it takes up quite a few lines of code. So where am I going with this? Well the other day I stumbled upon an incredibly useful function that is part of the jQuery library. And that function is the toggle() function.

The function allows you to set a number of actions that you would like to be cycled through and turns them in to a loop, essentially toggling the action taken. The first time the element is toggled, the first function specified is executed; the second time sees the second function executed, and so on. So, in my case, I was able to simply place some actions within the function and step back from all the complex JavaScript stuff. Let me show you what I mean.


The code above waits for the element named “button” to be clicked, and then fades-in an element named “popup” (I think you can see where this is going :) ). You can also use the function as a way of hiding and showing elements in turn, using code similar to the block below.

$("#button").click(function() {

The code above waits for the element named “button” to be clicked and then shows/hides all elements with a class of “.box” in turn. Remember that you need to set all the boxes you don’t want showing to begin with, to have a display value of none.

And that’s the toggle() function. It’s really simple and easy to use, and it has saved me a lot of time. I thought I better share it with you because it isn’t the best known function in the jQuery library, and it is one of the most useful! For more information on the function and some demos of it’s usage, visit the API.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s