In this tutorial, I am going to build sliding panels using the very popular Javascript library, JQuery
JQuery
Intermediate
In this tutorial, I am going to build sliding panels using the very popular Javascript library, JQuery. If you've never experienced JQuery before, I'd recommend walking through their Getting Started tutorial.
Let's start with the HTML code required to build the smallest example.
<div class="slidePanel">
<div class="slideHeader">Click Me</div>
<div class="slideBody">
Lorem ipsum.
</div>
</div>
Very simple. In fact the other three examples look identical to this one except the content is different. Here's the css that's required for these panels to actually look like panels.
.slideHeader
{
height: 20px;
background: Blue;
color: White;
}
.slideBody
{
background: Gray;
padding: 5px;
}
.slidePanel
{
width: 100px;
float: left;
margin: 5px;
} Now for the guts - the JQuery code to make it all work.
$(document).ready(function(){
//Fixes an animation glitch caused by the
//div's dynamic height. Need to set the
//height style so the slide functions work
//correctly.
$("div.slideBody").each(function(){
$(this).css("height", $(this).height() + "px");
});
//hook the mouseup events to each header
$("div.slidePanel").children(
"div.slideHeader").mouseup(function(){
//find the body whose header was clicked
var body = $(this).parent().children("div.slideBody");
//slide the panel
if(body.is(":hidden"))
body.slideDown();
else
body.slideUp();
});
});
First off, I have to say I was downright impressed at how little code I had to write to make this work. The first block of code might look a little strange, but with the content being dynamic, JQuery has no idea how tall it's supposed to be, and it needs that information to slide correctly. To get around it I loop through every sliding panel's body and set the height style to the actual height of the panel.
Next I use JQuery's Selectors heavily to attach a mouseup event to every header. I then use the selectors again to get the body associated with the header that was just clicked. Lastly, I determine which way to slide the panel based on whether or not the body is hidden.
This is one of my first introductions to JQuery and I can easily say I'm very impressed with how powerful it is. The combination of Visual Studio and the addition of intellisense support for JQuery made this one of the most enjoyable Javascript experiences I've ever had.