Script.aculo.us show/hide combinations (toggle function)
Sunday, October 28, 2007
I use script.aculo.us sporadically in different applications. Of course, too much of a good thing can ruin the essence of an application, and too much animation or thoughtless AJAXification can do this to a web site. We've all seen them: the ones that make everything disappear and appear at the blink of an eye without any user control. If we don't pay attention, AJAX could become what blink
was to the Web 1.0 era--hated by some, loved by others.
Tonight, I was trying to create a toggle section for a portion of a web page I was editing. I took a look at the
control, which is found in the
object. To use it, you code:
new Effect.toggle('ELEMENT_ID', 'THE_ANIMATION_YOU_WANT')
This is a very useful control; however, whatever object you click to make the magic happen doesn't change--at least, I couldn't find any documentation to do so. For example, lets say you have a link called "OFF" to make something disappear. I think that you would want the "OFF" link to turn to "ON," so you can make the something reappear. As in:
If you tried it, you see that the toggle action works, but the "OFF" link doesn't change to "ON," i.e., there is nowhere to specify what to change using the
function. (If you want to see the code, open it
in a new window.)
I did, however, found a solution to my requirement. The implementation of my solution looks like:
If you tried this version, you see that the toggling action works the same way as above, but the control object changes (with a gratuitous cool fading effect). I didn't use the
function, but I did use some of the functions available. (If you want to see the code, open it
in a new window.)
I think this toggling function is a very common requirement, but I just couldn't find a native solution that gave me any control over the toggling trigger--in truth, I didn't look hard enough, who has time for that.
Anyway, my solution would work for any type of trigger, whether it is a link, an image, or any element in the DOM hierarchy.
If you don't use script.aculo.us yet, you should give it a try
: you can code cool Web 2.0 effects that are "guaranteed" to work across multiple browser.