Simple Jquery and CSS menu
I’ve had some fun this weekend tinkering with Jquery. It’s taken me a long time to get round to playing with this library, having thrown my eggs in the Prototype / Scriptaculous basket, but after some experimentation, I wish I’d done it sooner!
I have to admit; the syntax is nicer, much simpler (no more $$(‘selector’)) and the documentation seems better. Jquery is also lightweight and fast.
To celebrate my switchover, here’s a very simple Jquery menu demonstration!
Let’s start off with the HTML:
<div id="”content”"> <ul id="”menu”"> <li class="”starter”>menu"></li> <li><a href="”#”">home</a></li> <li><a href="”#”">about us</a></li> <li>a href=”#”>portfolio</li> <li><a href="”#”">contact us</a></li> </ul> </div>
It doesn’t get much simpler than this! An ordered list, ready for styling. Not much to see here. Here comes the javascript:
$(document).ready(function(){
$("li:not(:first)").hide();
$("li.starter").click(function(){
if($("li:not(:first)").is(":visible")){
$("li:not(:first)").fadeOut("fast");
}else{
$("li:not(:first)").fadeIn("fast");
}
})
})Eek! Slightly more complicated. Let’s walk through it.
$(document).ready(function(){Before we do anything, we make sure that the DOM is ready for manipulation. This has a handy side effect, when we see the next line:
$("li:not(:first)").hide();This piece of code looks for all the ‘li’ elements in the page (disregarding the first one) and hides them, using display:none. The great thing is, since we’re doing this within $(document).ready, users with javascript switched off will still see the menu!
$("li.starter").click(function(){This tells the browser to look out for any clicks on the li.starter element, and use the next bit of code to handle it.
if($("li:not(:first)").is(":visible")){
$("li:not(:first)").fadeOut("fast");
}else{
$("li:not(:first)").fadeIn("fast");
}This part checks to see if the list items are visible, and shows them or hides them as appropriate.
You can see the full demonstration here, with comments!








