In this tutorial, we will be using jQuery to make a drop down box that fires on a click. Lets start with some css
background-color:#000;
font-family:Arial, Helvetica, sans-serif;
}
#container{
width: 500px;
margin: auto;
}
#top{
background-image:url(top.png);
width: 500px;
height: 67px;
}
#mid{
background-image:url(mid.png);
width: 440px;
padding:30px;
}
#bottom{
background-image:url(bottom.png);
width: 500px;
height: 40px;
}
The body styling is just to make our tutorial look nice. Then we have a container div which is will contain all our elements for the drop down. The first element is called “top”, which has a background image of the top of our box, with the words “click me”. As I’m sure you guessed, this is the element we are going to click to make or box expand. We have a bottom div called “bottom” which has our bottom image, and then we have our expanding div called “middle”. It has a background image which repeats. It has no set height, because the height will be based on the content of the div. It has 30px padding, so the width needs to be adjusted to make up for the padding (the width must equal the width you want (500px) minus the padding (60px made up of 30px left and 30px right)
The html is very simple, the only thing notable is that we give the expanding element (mid) a property of “display: none;” which means that it will be hidden at first.
<div id="top"></div>
<div id="mid" style="display: none;">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</div>
<div id="bottom"></div>
</div>
So the container has our 3 elements, and the expanding div has some content (Lorem Ipsum). Now for some jQuery magic!
$('#top').toggle(function(){
$('#mid').slideDown();
}, function(){
$('#mid').slideUp();
});
});
In our jQuery ready block, we have a toggle function. The toggle works with 2 functions, which it alternates through. Out first toggle function is fired when the user clicks on the element “top”. We call a jQuery slideDown() function on the element “mid”. The second toggle function is fired the next time we click the element “top”, and calls a jQuery slideUp() function on the element “mid”. Thats it for the jQuery, pretty impressive for so few lines of code!
As always, the source can be downloaded here and the demo can be seen here