JavaScript Toggler Class

January 14th, 2007

One of the most common things I do in javascript is show and hide several elements based on the clicking of a link. For this, I’ve created a simple toggler class which I’ll share with you now. You can see the latest version of the class in my repository or view the example.

An example of it’s use:

<script type="text/javascript">
  new Toggler('toggler', 'ul li.hide');
<script>

This would add an observer to a link with an id of toggler that would show and hide all elements that match the ul li.hide selector. I have a few other javascript classes that are kind of handy in my repository and I’ll post on them soon. I’m also thinking it might be interesting to do a little tutorial on how to use prototype to create classes.

5 Responses to “JavaScript Toggler Class”

  1. Looks pretty nice and it seems like a more versatile and extensible way of doing this kind behavior then some of the ways I’ve done this in the past. I’ll be sure to keep this script in mind. I also like you are keeping your javascript in a subversion repository.

  2. I’m liking having my javascript in subversion too. Anytime I make changes I just paste the whole thing in with the version update and boom it’s ready for the whole world. Works out pretty nice.

  3. This looks great, thanks for posting it. What changes could you make to this code to allow the hide/show status to be persistent? Could a cookie be created to remember the status and somehow the next time a user came to the same page the status of hidden/shown would be read from the cookie? Would you mind adding that if you know how? Perhaps a callback could be sent into the constructor with a function that sets the starting status?

  4. Yep, I would probably use a cookie. My toggled section class may be more what you are looking for. It uses cookies to remember hide/show status. It uses a cookie class I threw together.

  5. Great! I’ll take a look, thanks.

About This Site

Addicted to New is the personal website of John Nunemaker (Noo-neh-maker), a Web Developer enamored of Ruby on Rails and a wide-eyed fan of all things new and cool.