A simple animated collapsible panel in JQuery
How often does one have to write a collapsible panel? If you are a UI developer quite a lot - and how often have you wanted an animated one, if you are a UI developer who wants pizazz, like myself, you want it often.
But then comes the cross browser headaches and the pain of making it work consistently. I have been learning JQuery and it amazes me how painless JQuery can make this stuff.
Here is a simple example:
I start by writing a simple stylesheet (style.css):
body {
font-family: Arial, "MS Trebuchet", sans-serif;
}
.bd {
border: 1px solid #999;
}
Next here is my html page:
<html>
<head>
<title>jquery test</title>
<LINK href="style.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
//<![CDATA[
$(function() {
$("div.slider > div").addClass("bd").hide();
$("div.slider > a").click(function() {
$(this.nextElementSibling).slideToggle('fast');
});
});
//]]>
</script>
</head>
<body>
<h1>Test page for jquery</h1>
<hr />
<div>
This is some content
</div>
<div id="firstDiv" class="slider">
<a href="#">Click here to show this stuff</a>
<div>
This content will be revealed
</div>
</div>
</body>
</html>
Thats it - I express my collapsible panel with a marker style called “slider”. I next use a css selector “div.slider > div” to add a border to the content I wish to show and another selector element “div.slider > a” to add click handlers to my links. Since I really want to hide/show the content in the div next to the anchor element I use “this.nextElementSibling” to get to that div and simply call the slideToggle() method. The result is something like this:

Anytime I want a collapsible panel I just have to write a markup with a marker style like this:
<div class="slider">
<a href="#">Click here to show/hide</a>
<div>
Your content here
</div>
</div>
And the rest is taken care of by jquery. Simple, effective, pretty … love JQuery.
