Log

View Options

JavaScript Accordion

5/7/13

As a developer I have to often take "coding challenges". A recent one had a static picture of a menu that looked like an accordion menu. Being a coding challenge I didn't want to use some giant jQuery package, nor did I want to build a function to toggle each menu. The solution was obviously my own custom JavaScript class that modified the Document Object Model (DOM) based on simple naming conventions.

It's Pretty Easy
Simply follow the structure and the AccordionManager will do the rest!
  • Great for desingers who don't know or don't want to know JavaScript.
  • Add very little size to the overall page.
  • Super easy to implement.
Offers Control
The AccordionManager will reset the class attribute values on initialization and on click toggle, however you still have direct access to the CSS class names (see in the style tag above). Every other element you may style with what ever tagging/scripting you desire.
Expanding
Will I make updates? Probably not for a while (or ever), but feel free to expand on it and bend it to fit your needs. It's just a concept, it could go a lot of places from it's current state.

The JavaScript class will scan the DOM for any div tags with a class attribute value of "accordion_menu". Once an accordion_menu div is identified the AccordionManger class will turn every odd child div into an clickable title that will toggle the display of the proceeding even div tag.

Here is the source that made the above menu.

Snipt.net is dead. Replace link to "https://snipt.net/embed/efd74add272c58bb5e9d425d17dfb4db/"

I have tested this in Opera, Firefox, IE, and Chrome. It seems to work fine in all of them, even older versions. However use at your own risk, it is just an example after all. If you would like to use or expand on this little class, download the example package.