Clinton Montague

Developer, learner of things, functional programming enthusiast, hacker, and all round inquisitor.

Create cool slidy drawers with jQuery

November 16, 2008

Please note!! I have shamelessly stolen this article from my old and (even if I do say so myself) rather boring blog. So please ignore the terrible writing style! I’ll rewrite this article in the future, but until then, I present you with version 1.0

In this tutorial, I will show you how to make cool sliding content using jQuery. And the best part is that if javascript is disabled, the content will still display very nicely.

To ensure that the content degrades nicely, let’s first start off by creating the xhtml to display if no javascript is available. For the example I am using for this tutorial, I am going to create a set of three sliding drawers which will each contain a useful tool for the website. To do this, I will use an unordered list to contain the different tools with a title and the content for the tool. I will put the heading of each tool inside a span tag, and the content of the tool in a div with a class ‘hideMe’ so that later I can get jQuery to dynamically hide them.

  • Search

Now using CSS to style it up nicely, it is possible to end up with something looking similar to this, which looks nice enough to go live without adding the extra functionality – which is what graceful degradation is all about.

Adding the desired behaviour couldn’t be much simpler, believe it or not, the whole thing is done with something close to 20 lines of code thanks to jQuery. The first thing to do is to hide the content that needs to be hidden. Second, I will search for the span tag in each tool and remove the ‘slidyToolsBigTitle’ class (to stop styling it is a title) and add a anchor tag around it so that it is clickable. Finally, I will add the showing/hiding functionality to the new links when clicked.

$(function () {
	 * hide elements with class hideMe

	 * remove the slidyToolsBigTitle class and add the anchor tags

	 * find the new anchor tags and assign functions to them for when they are clicked
	 * (note: the jQuery each function works like php's foreach function)
	$("#slidyTools").find("li").find("a").each (function () {
	 	// the 'this' refers to the anchor tag from the each function
		$(this).click( function () {
	 	 	 // find all the tools and close them
			$("#slidyTools").find("li").find(".hideMe").each ( function () {
				// only close it if it's open
				if ($(this).is(":visible"))
			// open this section if it's hidden
			if ($(this).next().is(":hidden"))
			// that's it folks! (return false to stop the browser jumping the the '#' link
			return false;

And it’s as simple as that! Hopefully the comments in the code should be explanatory, but if you have any questions, feel free to leave a comment and I’ll get back to you with an explanation.