Today’s trick is using a better toggle method than the standard toggle function. Don’t get me wrong, it works great, but only if it is the only method for “toggling” the given element. Traditionally you pass is several functions, typically two. Function #1 that executes the first time that the event is fired, and a second function that fires the second time you click on it.
The problem arrises if you want to have more control over who, what, and where executes the toggles. Lets say you have a hidden div that is rather large, and a link above it that says “More Information.” You click the link, it fires Function A and it slides down the div. Since it is so big, at the bottom you of the div you put a link that says “Close.” The user clicks this link, and it hides the div again. The problem is the toggle function isn’t away that another part of the website hid the div. So if the user clicks “More Information”, it will still call Function #2, which will re-display the hiding annimation.
How do we solve this problem? Instead of using the toggle function, we write our own like so:
Better Toggle Method
// Assign Events on Page Ready
// Create Toggle Function
// If display is none, that means it is hidden
if($(‘#new .more’).css(‘display’) == ‘none’)
// Second Click
// Create Close Function
If you want to see an example of the old method, as well as the new method in action, you can see them here. Hopefully this can help you out.
4 thoughts on “jQuery Tip: Better Toggle”
Nice improvement to the toggle function.
hi, I have trouble with this nice function in my wordpress. can somebody help me how it could work? When I click on the link only a new page with the post is opened?! JQuery is enabled and other plugins with jquery work in my wordpress 😦
Thanks very useful tip !!!!
I too struggles alot to make click work perfectly !!! and ur solution is just perfect !!!! like toggle when we use toggle() with click its really produce buggy effect !!!!! either have to use bind() function or unbind() but this one is simple and running!!!!