Oct 7, 2008100

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

Got a question about this article? - Ask it here!

100 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.

  • Abhishek Dilliwal
    Jul 3, 2009

    Thanks for the post got to learn this in easy way :)

  • Dave
    Jul 7, 2009

    Still going strong!

    Excellent tutorial and the JQuery bit is super thanks.

  • Dave
    Jul 7, 2009

    @ other dave..

    You can get around this easily with css. Look into ‘z-index’ and the answer is there…

    Peace

  • Ryan
    Jul 28, 2009

    Thanks, Dave! You’re a lifesaver. And to the other “dave” – it’s those type of comments that have caused people to stop sharing useful information like this so freely…

  • WAMPvn
    Jul 31, 2009

    been searching all over Google for a non-complicated way to add reviews and ratings and it looks like this is it.

  • bobby
    Aug 12, 2009

    This menu do not fix well, as the dropdown push the below content down

  • BUG
    Aug 15, 2009

    Firefox 3.5.2 BUG, menu jquery :(

  • Shane
    Aug 21, 2009

    @bobby,

    Like was said here before,..

    Replace:
    #cssdropdown li.headlink:hover ul { display: block;}

    With:
    #cssdropdown li.headlink:hover ul { display: block; position:absolute;}

  • anirudha
    Aug 27, 2009

    i say that this is not useful for all browser in web so i use Mozilla extension for this For other browser i use simply css so all browser accept it
    then my script is worked but this script is too hard for learning my script check out mozilla css menu

  • jack smadi
    Aug 31, 2009

    thats really helpful , thank you

  • User of it
    Aug 31, 2009

    Great. Hope, took time to add this article with the snapshot on each steps and it worth thousands of people.

    Good commitment.

    Hats off.

  • Selva Comments
    Sep 1, 2009

    Thanks For this info….

  • Steve
    Sep 23, 2009

    Does anyone knows how to make ebay like drop down category button?

  • ChrisS
    Oct 12, 2009

    does anyone know how you would go about animating this so the menu reveals slowly and not instant?

  • JY
    Oct 14, 2009

    Hi,

    I followed your instructions and the drop down works great. Only problem is, it pushes the part of the site that sits below the menu (ie the content section) down whenever a drop down expands. What might I be doing wrong?!! Many thanks for any help you could offer on this. I’m going crazy trying to work it out (CSS is not my strong point)

  • Michael
    Oct 14, 2009

    Great menu. I integrated it into the wordpress archive dropdown. It works in Ie6, but the content below the menu shows through. I’ve tried setting z-indexs, but it hasn’t solved the problem.

  • Nauman Akhtar
    Oct 23, 2009

    Thank you so much for this great Drop Menu Menu CSS, it helped alot.

  • wie yoga
    Oct 28, 2009

    does anyone know how you would go about animating this so the menu reveals slowly

  • The People Say No!
    Nov 8, 2009

    This is very nice!! Easy to implement and highly customizable.

    @wie yoga:
    Uset the jQuery example and change the following bits:
    .css(‘display’, ‘block’) to .slideDown(“slow”)
    and
    .css(‘display’, ‘none’) to .slideUp(“slow”)

  • iwanttobelieve
    Nov 19, 2009

    Does anyone happen to know any plugin like this that support menu like this one: http://www.harborchulavista.com/

    Thanks in advanced!

  • Jorge
    Nov 20, 2009

    Thanks for the tutorial! .

    Can’t make it work with Flash.
    Flash is still in front of the menu.
    Where do you put the z-index in the css ?

  • Daniel
    Nov 27, 2009

    Thank a lot for this solution!

    I also had som problem with

    position:absolute;

    My problem was that apparently you have to use the strict mode for IE to have your fixed positioned element work properly. So when I inserted:

    at the top of my page it worked great!

    Hope this can help anyone!

  • Daniel
    Nov 27, 2009

    I saw that my comment did not work. But I found my solution at:

    “http://www.daniweb.com/forums/thread150830.html”

    Cheers!

  • Totty
    Dec 1, 2009

    ?????????

  • Totty
    Dec 1, 2009

    not surport chinese!my god!

  • bamboolabcode
    Dec 5, 2009

    It’s exellence code.

  • sana
    Dec 10, 2009

    Hi

    I have a slide show that I’ve downloaded from your site and which is running perfectly. On top of the slide show I have a drop down menu. Unfortunately it opens behind the images, which makes it impossible to select the links. How to solve this problem?

    Thank you

  • bockerl
    Dec 17, 2009

    Thank you … this has me very helped.

  • webdev
    Dec 24, 2009

    How can a person update a jQuery menu from a central file (like XML for example) if the html “ul” and “li” menu structure must be pasted from page to page? How do you update the menu if you have, for example 50 pages, without having to edit page by page and not being able to use Server Side Includes?

  • wespai
    Dec 27, 2009

    thx collect it to

    ajax.wespai.com

  • selva comments
    Jan 5, 2010

    great realease and thanks for sharing

  • tom
    Jan 9, 2010

    got an issue with ie7 and this line
    #cssdropdown li.headlink:hover ul { display: block; position:absolute;}

    everything works fine but drop down menu is not under parent but moved to right for about 200px, tried many things but can’t figure out how to fix it…any ideas?

  • tom
    Jan 10, 2010

    added left:0px to #cssdropdown li.headlink ul
    and looks that problem is resolved in ie7

  • Damien Darwick
    Jan 12, 2010

    Hey thanks for the info, was looking for a way to sort a menu that was showing improperly and found it here!

  • Tom
    Jan 20, 2010

    i’ve seen better jquery menu scripts …

  • Harry
    Jan 23, 2010

    thanks for resources

  • ajans?
    Jan 24, 2010

    thats really helpful , thank you:)

  • Akj Infinity
    Feb 1, 2010

    Folk ur great !!! … quite simple and effective. You’re the man, 4real, your the man !!!

  • adrie
    Feb 6, 2010

    Please give us another tutorial that focuses on making this menu a multi-column menu. Thank you!

  • jan
    Feb 10, 2010

    Nice menu! Still a shame IE has to have some javascript to function properly.. Hopefully soon we can just use css with the :hover functionality.

    To place it over any kind of flash movie you have to publish your flash movie with wmode=transparant in and it will fix any html layers on top of the flash..

    cheers

  • Pankaj
    Feb 11, 2010

    Nice work…Thanks for sharing..Is there any other article on Menu using JQuery?

  • Rich
    Feb 18, 2010

    Great stuff. However, I still can’t get the absolute position to work in any browser and the menus are pushing down the content below.

    Any help would be appreciated.

  • Newton Pasqualini Filho
    Feb 21, 2010

    Man, you are “the one”!!!

Leave a Comment

Ask a Question at Design Reviver Answers