Collapsible Menu with jQuery

7th Mar 2010 05:44am

To begin with we need to make a menu, which I've just done a quick temporary 5 items in mine using the HTML lists tags.

<menutitle>Main</menutitle>
<ul id="menu">
<li><a href="#">Item 1</a></li>
<li><a href="#">Item 2</a></li>
<li><a href="#">Item 3</a></li>
<li><a href="#">Item 4</a></li>
<li><a href="#">Item 5</a></li>
</ul>

Then in the header of your page, you will need to call your jQuery file.

<script type="text/javascript" src="jquery.js"></script>

Now beneath the line where you're calling your jQuery from, you will need to write some more JavaScript to tell the document to run the later bit of code when the document has loaded.

<script type="text/javascript">
$(document).ready(function(){

});
</script>

Now the document is ready for your jQuery code, we need to tell it that when the "title" bit of the menu (which we've tagged as <menutitle>) is clicked, it should slide it closed.

<script type="text/javascript">
$(document).ready(function(){
$("menutitle").click(function () {
$("#menu").slideToggle("slow");
});
});
</script>

The above code will toggle the sliding action of anything we've put id="menu" on, which is why we've put it on the <ul> bit. Now with everything put together and saved, you should have a menu that toggles closed and open when you press the top bit, which in my example is "Main"

Please Note
Please note though, that this is just an example of doing a menu that can open and close. You can use a cookie to saved if you've closed the menu so that when you refresh the page it stays closed or you can style the menu nicely with CSS. You can also use this method for anything if you wanted from showing and hiding an image, paragraphs, forms, buttons, flash applications, etc...

You can get hold of the latest copy of jQuery from the jQuery website.

Read and Leave a Comment 1 Comment(s) -:- Permalink
Tags: jquery, tutorial, menu, sliding

Latest News Stories
» Pectus Excavatum - Catchup
» Pectus Excavatum - The Final Chapter
» Pectus Excavatum Operation
» One Dream That Won't Be Fulfilled...
» Hotpoint WIXXE127 on Twitter Trends
» Google StreetView: Superheroes found in Blackpool
Top Viewed Stories
» PHP Mini Message Board Tutorial (40,846)
» Bypass Photobucket (32,474)
» PHP Search Engine Tutorial (29,359)
» Getting .htaccess on AppServ (Windows) to work (23,648)
» Rare McDonalds Monopoly 2008 Tickets (11,948)
» Helen Willetts Pregnant? (9,558)
Most Commented Stories
» PHP Mini Message Board Tutorial (101)
» PHP Search Engine Tutorial (37)
» Create your own Image Uploader (23)
» Pectus Excavatum (20)
» I like my DuMP (15)
» New Shameless Trailer! (10)