jQuery Toggle Menu
I cannot begin to count the numerous occasions JavaScript has saved my butt during a design project. We have all being there, we hate to admit it, but CSS just won’t do it. However, JavaScript is not the most easy to pick up programming language out there, until now. Thanks to jQuery, a JavaScript library, writing scripts has never before being so easy and enjoyable. Lean more about jQuery by visiting their official site. Now, let’s take a look at how jQuery can be of use to you.
The Problem
Not so long ago, I was presented with a project that required the use of an archival drop down menu. However, this was a newspaper site and the number of archived issues was extensive. So, how do you fit a drop down menu of this magnitude anywhere on your design? jQuery.
The Solution
The basic idea is to use jQuery to hide the drop down menu and only make it visible when an HTML element is clicked. Let’s take a look at the first part of the script.
jQuery(document).ready(function()
{
var content = [".issueLabel",".issueBox"];
if (content)
{
if(content.length == 2)
{
var toggler = content[0];
var togglee = content[1];
menuToggler(toggler,togglee);
}
else alert(”Too many togglers or togglees, check your meta tag content.”);
}
else alert(”Nothing to toggle”);
});
The code above makes a size-2 array with the toggler and togglee elements. Its content is looped and checked for properly formating. If so, a function that will do all the “heavy” work is called.
function menuToggler(toggler, togglee)
{
var original_text = $(toggler).text();
$(togglee).hide();
$(toggler).toggle(
function()
{
$(toggler).text("Close Archive Menu");
$(togglee).show("slow");
},
function()
{
$(togglee).hide("slow");
$(toggler).text(original_text);
});
}
I like to believe that jQuery is easy to read but I know this may be because I have been using it for several projects now. In any case, the “menuToggler” take two parameters. The toggler and the togglee. The togglee is the element you want to hide unless requested, in this case by a click. The toggler is the element that, when clicked, makes the togglee visible.
First, we have to save the original text of the toggler, you will see why later. After doing so, the code hides the toglee element and ses the toggle function on the toggler. If clicked once, the toggler’s text will be replaced with “Close Archive Menu” and the toglee will be made visible. If clicked again, the toggler’s text will be replaced with its original text and the toglee will be hidden again.
Final Thoughts
JavaScript should be your last resource when it comes to web design. All the design aspects of your project should be kept in the CSS. This helps keep the CPU required to run your site to the minimum and allows a greater audience to enjoy your design at its fullest, as some people may have JavaScript disable. I hope this is script is of some use to you. Leave comments and/or questions, they are greatly appreciated.

