Thursday, August 9, 2012

Cycling through multiple functions

Sometimes you may want to click an item and cycle between 2 (or more) different functions - for instance first show, then hide another item.  This may be for building a custom navigation, displaying additional options, or any other scenario where you want to have an on/off type of functionality.

For a single function, you would bind to the click event like this:
With the toggle event, you can assign as many different functions as you find necessary, and cycle through them starting at the top and repeating in a loop. For instance, if you need to show 2 different versions of help (initially hidden) you would cycle between
  • No help
  • Brief Help
  • Full Help
To accomplish this, you would use the toggle event and set up three functions. The first click displays a hidden div for partial help. The second click displays another hidden div which contains the extra help not covered by the brief section. The third click hides both. Full code for this is below. To change the content of the link so the user knows what to expect, you can use the text function. Just to keep you on your toes, there is also an animation function named toggle as well... They have the same name but are used very differently. The animation function simply turns on or off a given element. Using toggle as an event (above) you attach it to the button and tell it what to do each time the button is clicked. Using toggle as a function, you would attach it to the hidden element inside a click handler, like this:

See it in action!

Experiment with both of these at jsFiddle:

No comments:

Post a Comment