Oct 7, 200857

jQuery & CSS Example – Dropdown Menu

Dropdown menus and menu bars have been heavily used since the early days of graphical user interfaces. Their use has become ubiquitous, and even expected, in desktop applications, and the web has quickly followed suit. This article is intended to describe an extremely basic, yet extremely powerful, technique for adding dropdown menus in your application user interface or website design.

The Finished Product

Getting Started

To begin, we need to define our basic menu hierarchy. In order to maintain a structured and semantic approach to this, we will use nothing more than unordered lists of standard links. We’ll use the following code as an example:



<ul id="cssdropdown">
<li class="headlink">
	<a href="mine.html?search_engines">Search Engines</a>
	 <ul>
	  <li><a href="http://google.com/">Google</a></li>
	  <li><a href="http://yahoo.com/">Yahoo</a></li>
	  <li><a href="http://live.com/">Live Search</a></li>
	 </ul>
	 </li>
	  <li class="headlink">
	  <a href="mine.html?shopping">Shopping</a>
         <ul>
	  <li><a href="http://amazon.com/">Amazon</a></li>
	  <li><a href="http://ebay.com/">eBay</a></li>
	  <li><a href="http://craigslist.com/">CraigsList</a></li>
	 </ul>
 </li>
</ul>

You should see something like this:

Basic Unordered List of Links

Creating Dropdown Lists

With our semantic HTML and link structure written out, we can proceed to apply some basic hover techniques that are included in CSS. The :hover pseudo-class is invoked when the mouse is placed over the list item.

We can use CSS to hide the child unordered lists by default, and show them with the :hover pseudo-class, like so:


       li.headlink ul { display: none; }
       li.headlink:hover ul { display: block; }

It is best to take this opportunity to apply some basic styling to the list, such as floating the parent unordered lists in a row, and specifying the width of the unordered list to ensure that no shifting occurs when the elements are hidden or shown. This should look something like this:

The Basic Styling Applied to the Unordered List of Links

The Issue with Internet Explorer

Unfortunately, while the :hover pseudo-class may be elegant, it does not work in Internet Explorer. At this point, a short bit of JavaScript is required to provide a clean fix. All we need to do is select all unordered lists that are within a list item that has the class .headlink and add onmouseover and onmouseout events to them. This can be done in twelve simple lines of code:


	window.onload = function()
	{
		var lis = document.getElementsByTagName('li');
		for(i = 0; i < lis.length; i++)
		{
			var li = lis[i];
			if (li.className == 'headlink')
			{
				li.onmouseover = function() { this.getElementsByTagName('ul').item(0).style.display = 'block'; }
				li.onmouseout = function() { this.getElementsByTagName('ul').item(0).style.display = 'none'; }
			}
		}
	}
	

Those using jQuery are privileged to an even easier solution:


	$(document).ready(function(){
		$('li.headlink').hover(
			function() { $('ul', this).css('display', 'block'); },
			function() { $('ul', this).css('display', 'none'); });
	});
	

Putting It All Together

The dropdown menu is now functional in the major browsers, and is ready to be styled, cleaned up, and shipped.

It is advantageous to start by applying a basic style that's a little more appealing than the standard lists. This allows us to visualize how this will fit into our application or design.

Standard Styling on Dropdown Menu

Adding Some Flare

With a few extra lines of CSS, the menu is styled and ready to fit into our site.

Wrapping Up

One important aspect of writing a generic dropdown list is to segregate the CSS and JavaScript to ensure that there are no conflicts. The easiest way to do this is to add the #cssdropdown selector in front of every element.

Finally, we check to see if the #cssdropdown div can be moved around freely. This ensures that dropdown menu we have created will flow nicely when integrated with our existing site design or application user interface.

The full code and example remains both basic and concise to exemplify the simplicity of the underlying technique for using dropdown menus on your website. Enjoy!

Tutorial kindly written by Nathan Wong

57 Comments

  • George
    Oct 7, 2008

    This one’s going in the bookmarks. I was looking for a clear explanation of this. Some tutorials I’ve seen have lines and lines of unnecessary markup. Thanks for keeping this simple.

  • Brandon Cox
    Oct 7, 2008

    Awesome tutorial and example. Drop downs consume a ton of hair-pulling time for me – I appreciate the help!!

  • iddaa
    Oct 8, 2008

    Very nice blog http://designreviver.com/

  • Dainis Graveris
    Oct 8, 2008

    Nice tut and inspirational outcome! :) I needed detailed tutorial like this – so thanks, appreciated!

  • Nathan Wong
    Oct 8, 2008

    I’m glad you guys are making use of the tutorial. I appreciate the kind words. Keep an eye out over this coming week for a handful of jQuery/CSS tutorials on various common UI elements! :)

  • utchanovsky
    Oct 9, 2008

    Wow, cool tutorial. I’ll bookmark this. Thx a lot

  • Blaketdet
    Oct 9, 2008

    Thangs …Bro

  • Martin Sarsini
    Oct 10, 2008

    It’s a good simple system. But if you are looking for more complex stuff, more personizable options, compatibilty with flash z-index etc… jdmenu is the best

  • Tim
    Oct 10, 2008

    What about adding a delay to the mouse out event? That way if you accidentally move the mouse the wrong way, it won’t close the pulldown. This helps when the dropdowns get complicated (with sub-dropdowns, etc). Do you have an easy way of doing this? Or perhaps adding a slower animation to the pulling down of the menu, that would help to. I realize your purpose of making it simple, and that’s awesome. This is one the simplest and best described tuts on this I’ve seen.

  • iso 17025
    Oct 10, 2008

    Great article! Very useful.

  • Rahul
    Oct 11, 2008

    very nice. I like CSS examples and am also inclined towards jQuery as well.

  • Ap
    Oct 11, 2008

    @Tim: I second that!

  • Zafar Iqbal
    Oct 11, 2008

    It really is a nice example, showing in simple but still with some details about setting up a nice one level CSS drop-down menu. Addition of jQuery also enhances its usability.

    Thanks for the effort.

  • Kim Guanzon
    Oct 11, 2008

    Is it possible to create a multi column div that drops down from each category like johnlewis.com?

  • Alek
    Oct 13, 2008

    Very good tutorial. Nice and simple.

  • Delhi City India
    Oct 14, 2008

    Hey,
    Great Job……
    Nice tutorial

  • Nathan Wong
    Oct 14, 2008

    Kim: Yeah, you could use a div instead of an unordered list for the dropdown part and you should be able to float within it without too much trouble. It would take some changes, but overall wouldn’t be too hard. Post a comment up if you try and can’t get it working. :)

  • new york web design company
    Oct 15, 2008

    hi. this really helped me out a lot. i am happy.

  • David Simmer
    Oct 15, 2008

    Nicely done. Minor nitpick: we should add visual “flair,” unless the menu is intended to light on fire, in which case “flare” would work :)

  • shubelal
    Oct 17, 2008

    Nice work I am going to use this. thanks

  • James Curran
    Oct 17, 2008

    Now, is this just me?

    I can view this page fine in IE, but in FireFox I can see the comments, but not the article itself.

  • Cam Peterson
    Oct 17, 2008

    Nathan, I love the tutorial and find it working well with Safari and Firefox. I am having a bit of trouble with Internet Explorer. When using the javascript, it bumps the text nested in a div out of its way. In FF and Safari the dropdowns show up over the text. Any thoughts? I am using it at http://www.aviationutah.com.

    Thanks,
    Cameron Peterson

  • Fred Campbell
    Oct 19, 2008

    Thank you so much for such a clear and concise tutorial.

  • Nathan Wong
    Oct 22, 2008

    Cam: What version of IE? I only have access to IE7 at the moment and it’s looking fine for me. Or have you fixed it yourself? Thanks for the kind words. :)

  • MaxBidAuctions.Com - Online Auctions
    Oct 27, 2008

    This is Great Creating Dropdown Lists will come in handy, when we create our favorite Links Page!

    Thanks
    BOB

  • Shaun
    Oct 28, 2008

    Hey, first off this is a really good example of a drop down. Very simple, very solid and very easy to alter.

    But I’m having an issue with the popup sometimes showing behind content on the page. Is there any way of changing the z-index so it’s always in front?

    Thanks
    Shaun

  • Shaun
    Oct 28, 2008

    Ignore me, it was very simple, in case anyone else has a simular issue. Just add a high number (eg. z-index:10) to the CSS and it will always be in front. If you have flash files don’t forget to set your Flash files to wmode=”transparent”. Everything should work fine and dandy.

  • Nathan Wong
    Oct 29, 2008

    Glad you found a solution, Shaun, and thanks for sharing with the rest of us. :)

  • ryu
    Oct 30, 2008

    Really cool…
    Keep it up !!

  • indi_sign
    Nov 14, 2008

    :)
    This is great tutorial, but why to use jquery if you can make exactly the same effect/stuff with pure html and css, which will be accessible all the time, with enabled/disabled JS.

    Great tut anyway, helps a lot to understand the basics of jQuery.

  • Nathan Wong
    Nov 19, 2008

    It’s that IE doesn’t support the CSS :hover pseudo-element on anything but anchor tags. The JS is used to make IE work. I know, it’s disappointing we can’t just use CSS, but that’s the hand we’ve been dealt. :) Glad you like it!

    - Nathan

  • Kristoffer
    Nov 20, 2008

    Hi Nathan, I have a problom with this. When I dont Hover the menu, the page looks great, but when I hover it, the submenu pushes everything on the page down.. I would like the menu to be ontop of the content of the page.

    Am I doing something wrong? Great tutorial!

  • WhoMe?
    Dec 3, 2008

    I’m sorry but I thought this tut was HORRIBLE! I am new to web design and I don’t know where to paste this information. Is it in the HEAD or BODY section. What name do I save the CSS file? Etc….

    Please remember that some in your audience are completely new to java/html/css.

    thanks

  • Miranda Adria
    Dec 7, 2008

    This tutorial was very helpful. I’ve used it for my own website as a tree menu.

    How could I tweak this coding so that whenever the headlink is clicked, the options below stay open until something else is clicked?

    Thank you.

  • Radek
    Dec 28, 2008

    I’ve been looking for some simple drop down using CSS and jQuery, I’ve just bookmarked yours. Must say, I got a bit worried when I was reading the lines …getElementById…is this a CSS + jQuery tutorial? I soon realized why was it there :) Thanks for this tutorial!
    Radek

  • pflynn
    Jan 7, 2009

    Got to say Nathan great tut! Cheers for putting it out there!

  • Frank
    Jan 16, 2009

    Hey – I just found this awesome jQuery Cheat Sheet for the iPhone. I’ve only had it for a day and it’s been really helpful.

    http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=302090867&mt=8

    Looks like there’s also a CSS Cheat Sheet from the same guys.

    http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=301093674&mt=8

  • Jeremy
    Feb 12, 2009

    I unfortunately cannot get this to work on IE 6/7 at all. When you rollover Collections in the navigation, it uses this tutorial drop down in Safari / Firefox beautifully. However, I’ve referenced the javascript in an external file called jquery.dropdown.menu.js. But, no matter which version I use of the javascript code vs. jquery code, I am unable to get it to work. Any suggestions?

  • paul
    Feb 17, 2009

    kristoffer,

    Add position: absolute to this line
    #cssdropdown li.headlink:hover ul { display: block; position:absolute;}

    this stops the items to take up space in the document flow.
    I haven’t tested thoroughly so maybe it might break something else.

  • alex
    Feb 28, 2009

    hi huys, i need some ideas for a dropdown menu with jquery; i have 3 divs that will be the buttons and 3 divs that will contain the submenus(so each of these three divs will contain some links). to be easier we’ll take for this discussion just one div that will be the button and one div that will be the submenus container(this one is placed above the button div). So…i want when the mouse hovers the button div….the submenu div to show-up…and when the mouse leaves the button the submenu div to disappear. ok…i made this using the jquery’s .hover() adding and removing a class that shows and hides the element(visibility:none). but the problem is that i want on page load the submenu div to be hidden (i tried to simulate user interaction but it didn’t work, i don’t know why ’cause i’m very new to jquery :P , i don’t know where to place the trigger code).

    ok….the big problem is how to make the submenu div not to disappear when the mouse leaves the button area but enters the submenu div area.(the button div and the submenu div are one next to each other)

    any help will be appreciated :P

  • steve
    Mar 19, 2009

    First, thanks for the tutorial. I get CSS dropdown navs now, but Im having the same issue as Kristoffer: when the hover state happens the flow of the site is adjusted for the new elements becoming visible.

    I dont want this. I want the nav to appear above the content of the site? Maybe use a z-layer, but I dont know how or even if that would work here.

    Example:
    http://www.hattersworkshop.com/ftp/csc/index.html

    I tried making different elements position: absolute, but this was always causing a problem in FF 3 where the nev child elements appear behind the text and only become visible when hovered… very strange.

    Thanks to anyone for any working solution they come up with.

  • steve
    Mar 19, 2009

    Played with my code some more and got it.
    Paul’s comment was right on.

    Thanks.

  • Danny
    Apr 8, 2009

    Thanks for the tutorial. Though I still have problems between the drop down list and the flash player, I’ve worked around it.

  • ARTI
    Apr 17, 2009

    It works fine on my version of Firefox 1.5.0.1 Perhaps you don’t have the latest version. I run an image gallery myself, but I don’t think type of layout would art? work very well for me as I have descriptions for my images and some of the images are quite large. I don’t know, it might be worth experimenting with.

  • Meg
    Apr 17, 2009

    I love this menu, Nathan. Thanks. Question: Is there any way to increase the space between the navigation item and the menu that drops down from it? My website (in development) is here: http://64.253.36.100/BartolomeiPucciarelli2009/. I would like the drop down to appear below the shaded horizontal bar. (Or do I just have to rework the graphics?) Thanks!

  • kuflu
    Apr 21, 2009

    thanks very nice menu

  • Quin
    Apr 24, 2009

    mola… me encanta!

  • Sunny
    May 12, 2009

    Thanks! This was a very clear and precise explanation. Continue the good work!

  • akkumaru
    May 13, 2009

    great!
    i thank you!

  • Jared
    May 22, 2009

    Looks great. I’ll use this in an upcoming website re-design – the current drop-down code has been added to several times and has become unmanageable. I’ll remember the z-index. Thanks!

  • webfixeddotnet
    May 24, 2009

    Superb!!!

  • ismail
    May 28, 2009

    thank’s to share knowladge,.i think your site very good for knowladge.,

  • Webagentur
    Jun 3, 2009

    Thank you … this tutorial has me very helped.

  • bolo
    Jun 7, 2009

    good post!thank you,i’ll repaint it.

  • mtho
    Jun 9, 2009

    simple!!, i like it

  • mm
    Jun 18, 2009

    Thank you very much for the explanation. It’s easy to do, but, how about if I want another dropdown menu inside the second level?

    This example is for 2 levels, somebody could tell the modification to achieve 3 levels??

    Thank you very much.

  • dave
    Jun 30, 2009

    mr swarm,

    the menu displaces everything when the drop-downs trigger, so it is useless to any website that might actually want to look serious.

Leave a Comment