Friday, May 29, 2009

jQuery drop down menu: principles

Creating a drop down menu with jQuery makes Your life simpler and easier.

On this tutorial, we'll try to create a simple (yet a nice one!) drop down menu, powered with pleasure by jQuery.

First, we start with the HTML. Our basic menu form will look like this:

  • 1. Item

  • 2. Item

    • 2.1. Item

    • 2.2. Item

      • 2.2.1. Item


Code:

<ul id="top">
<li class="head">1. Item</li>
<li class="head">2. Item
<ul>
<li>2.1. Item</li>
<li>2.2. Item
<ul>
<li>2.2.1. Item</li>
</ul>
</li>
</ul>
</li>
</ul>

Cheese! Our list-based menu will support multiple submenu.

Next is CSS:

/* No list-bullet! */
#center ul{
list-style: none;
}

/* start menu at most left */
#center ul#top{
padding-left: 0px;
}

/* horizontal (head) menu */
ul#top li.head{
float: left;
padding-left: 10px;
}

/* style for submenu */
ul#top li.head ul{
position: absolute;
display: block;
}

The CSS is quite simple and clean. You can add your own CSS code for beautiful styling.

Last, the javascript. Yes, we need to enable the browser's Javascript support.
At head section of Your html file, add a reference to a jQuery library file:

Code:

<script language="javascript" src="jquery.js"></script>

Then we add these simple lines on script section:

Code:

jQuery(document).ready(function(){
jQuery("#top ul").css({display: "none"});
jQuery("#top li").hover(
function(){
jQuery(this).find('ul:first').css({visibility: "visible", display: "none"}).show(600);},
function(){
jQuery(this).find('ul:first').fadeOut(450);}
);}
);

What does it mean?

First, we tell the browser to hide ({display; "none"}) the submenus. Second, we tell that if the head menu item is hovered, its first submenu should appear (show(600);), slowly. Then it should fade out (fadeOut(450);), again, slowly. Of course, You may change the numbers as You find it fits; the greater the number, the slower it would be.

That's it!

No comments:

Post a Comment