Create Simple Dropdown Menu Using jQuery

In this post, we are going to create a simple dropdown menu with the help of jQuery, take a look at the demo of it first. I assume you know at least the basics of jQuery and CSS. The key to creating the dropdown menu is to use the CSS’s properties: position, top, left, z-index.

Create Simple Dropdown Menu Using jQuery

With these properties, we make sure that dropdown menu appears exactly below the hovered link and over any other element. We then make sure that when mouse is over a link, we show the corresponding dropdown menu and when mouse is away, we hide it back. For these events, we use the jQuery’s mouseenter and mouseleave methods. So that’s all we need to know to create the dropdown menu, pretty simple stuff !

You may be interested in the following related articles as well.

Feel free to join us and you are always welcome to share your thoughts that our readers may find helpful.

Don’t forget to subscribe to our RSS-feed and follow us on Twitter — for recent updates.

Final Result Demo and Download

Here is what we will making, click on the link below to see the live demo.

HTML

Here is how the html looks like for each of dropdown menu:

<div id="container">

 <!-- First Menu Start -->
  <ul>
  <li><a href="#">Menu One</a></li>

 <li>
  <a href="#">Link 1</a>
  <a href="#">Link 2</a>
  <a href="#">Link 3</a>
  <a href="#">Link 4</a>
  <a href="#">Link 5</a>
  </li>

 </ul>
  <!-- First Menu End -->

 <!-- Second Menu Start -->
  <ul>
  <li><a href="#">Menu Two</a></li>

 <li>
  <a href="#">Link 1</a>
  <a href="#">Link 2</a>
  <a href="#">Link 3</a>
  <a href="#">Link 4</a>
  <a href="#">Link 5</a>
  </li>

 </ul>
  <!-- Second Menu End -->

 <!-- and so on -->

 </div>

As can be seen, we are going to use the unordered lists for our dropdown menu. Each menu link is given a class of dropdown and dropdown itself has been wrapped in a list with class of sublinks. These class names will be utilized by jQuery to decide which menu to show.

CSS

Here is the CSS for the dropdown menu:

/* CSS For Dropdown Menu Start */
  ul
  {
  list-style:none;
  padding:0px;
  margin:0px
  }

ul li
  {
  display:inline;
  float:left;
  }

ul li a
  {
  color:#ffffff;
  background:#990E00;
  margin-right:5px;
  font-weight:bold;
  font-size:12px;
  font-family:verdana;
  text-decoration:none;
  display:block;
  width:100px;
  height:25px;
  line-height:25px;
  text-align:center;
  -webkit-border-radius:5px;
  -moz-border-radius:5px;
  border: 1px solid #560E00;
  }

ul li a:hover
  {
  color:#cccccc;
  background:#560E00;
  font-weight:bold;
  text-decoration:none;
  display:block;
  width:100px;
  text-align:center;
  -webkit-border-radius:5px;
  -moz-border-radius:5px;
  border: 1px solid #000000;
  }

ul li.sublinks a
  {
  color:#000000;
  background:#f6f6f6;
  border-bottom:1px solid #cccccc;
  font-weight:normal;
  text-decoration:none;
  display:block;
  width:100px;
  text-align:center;
  margin-top:2px;
  }

ul li.sublinks a:hover
  {
  color:#000000;
  background:#FFEFC6;
  font-weight:normal;
  text-decoration:none;
  display:block;
  width:100px;
  text-align:center;
  }

ul li.sublinks
  {
  display:none;
  }

/* CSS For Dropdown Menu End */

Most of the CSS is there for styling the menu (although you can style it even better if you want) but here are some of the important things to note in that CSS:

1 - We remove the bullets from lists using list-style:none;

2 - We know that lists are block-level elements and always appear vertically. In order to make it appear horizontally, we make them inline elements and float them to left with:

display:inline;
float:left;

3 - The links by default are inline elements, we make them block-level elements with display:block; so that we could apply a width to them.

4 - Initially we hide all dropdown menus with:

ul li.sublinks
{
display:none;
}

jQuery

Imagine the old days, creating the dropdown menu with raw javascript, well a lot of code ! but this is all we need with jQuery:

$(function(){
  $('.dropdown').mouseenter(function(){
  $('.sublinks').stop(false, true).hide();

 var submenu = $(this).parent().next();

 submenu.css({
  position:'absolute',
  top: $(this).offset().top + $(this).height() + 'px',
  left: $(this).offset().left + 'px',
  zIndex:1000
  });

 submenu.stop().slideDown(300);

 submenu.mouseleave(function(){
  $(this).slideUp(300);
  });
  });
  });

Pretty easy stuff there actually, let me explain how. First and as usual, we wrap our code in jQuery’s ready handler:

$(function(){
...
});

We run our code when mouse enters (mouseenter method) an element with class set to dropdown ($('.dropdown')), the menu link in our case:

$(function(){
$('.dropdown').mouseenter(function(){
........
});
});

We make sure that we hide (hide()) all previously open dropdowns when mouse enters a menu link:

$('.sublinks').stop(false, true).hide();

Note the stop function there, it helps us to show only one dropdown at a time when mouse is quickly hovered over various menu links. If we did not use it, each dropdown menu will remain visible unless we move our mouse arrow away explicitly. That is basically known as queue buildup so we avoid that with stop function there.
We then grab the actual dropdown menu to be shown with and store in into a variable:

var submenu = $(this).parent().next();

If you look at the html:

<!-- First Menu Start -->
  <ul>
  <li><a href="#">Menu One</a></li>

 <li>
  <a href="#">Link 1</a>
  <a href="#">Link 2</a>
  <a href="#">Link 3</a>
  <a href="#">Link 4</a>
  <a href="#">Link 5</a>
  </li>

</ul>
  <!-- First Menu End -->

When a link with class dropdown is hovered, we move back with parent() ending at <li> and then with next(), we reach at our desired dropdown menu, <li> with class sublinks. So this is basically how jQuery makes it easy for us to find which dropdown to show when a particular menu link is hovered upon.

After that, we apply some CSS to the dropdown so that it appears exactly below the hovered menu link:

submenu.css({
position:'absolute',
top: $(this).offset().top + $(this).height() + 'px',
left: $(this).offset().left + 'px',
zIndex:1000
});

That code is very important as it makes sure that dropdown appears exactly below the hovered menu link. With position set to absolute, we can position the element at any place on the document independently. We then get the top position of the hovered menu link with $(this).offset().top (this refers to current hovered menu link) and add to it the height of it so that dropdown appears exactly below that link. We do something similar for the left property. We then use the z-index property to make sure that dropdown appears over everything else.

And then we show the dropdown while sliding it down with slideDown at the speed of 300 millseconds with:

submenu.stop().slideDown(300);  

Of course, you could have used other methods of animation such as fadeIn, animate with custom animation styles.

Now this far it was about to show the dropdown. It is time to hide it when the mouse leaves it. We do so with this piece of code:

submenu.mouseleave(function(){
$(this).slideUp(300);
});

To hide the dropdown, we use slideUp, the opposite of slideDown. Note that submenu is a variable we had created earlier to denote the dropdown.

So that was all there is to creating a single-level dropdown menu with jQuery.

Image Credits

Like it? Share it.

76 Comments

  1. Good improve ^^

    • i studied a lot!

  2. Whatever happened to progressive enrichment/enhancement? The whole thing doesn’t work without Javascript – even though you’re perfectly capable of building a dropdown/foldout menu using only CSS in any browser above IE7. Even for IE6 you just need a simple fix to allow a hover over another element than an anchor…

  3. Thanks budy nice move

  4. @Pim Derks: Yes you are right, It is absolutely possible to create a dropdown menu using CSS and to support IE6, we would have used the javascript but for in this post I just wanted to show how to create one using jQuery.

  5. It was really nice post!
    Thanks a lot for sharing..

  6. Really awesome post. I have learned a lot. Thanks for sharing.

  7. Great menu. Thanks for this tutorial

  8. I have a question I would like the item above remain illuminated while the mouse pointer is over a submenu item, is there a simple way to get it? sometimes the menu gets displayed even when not being targeted, is there a way to improve it?

  9. good plugin

  10. Great Post..!!

  11. ugh still can’t get it to work. do you have any video tutorial?

  12. Thanks for posting this tutorial. It’s nice to see how a dropdown can be done with so little code, the jQuery library really speeds up and simplifies coding basic effects. My briefs require my work to operate correctly in IE6 + so i don’t think i will use it professionally.

  13. @David: Yes, this will even work in IE>=6.

  14. This is some great information

  15. Yes you are right, It is absolutely possible to create a drop-down menu using CSS and to support IE6. I just wanted to show how to create one using j Query.

  16. It is a great information.Thank you share your thougths with us,

  17. Great!.. thank for this tutorial

  18. I really like the smooth dropdown effect and the implementation is quite simple. However, there is a problem on IE7 when you have a text with link under the menu, the dropdown disappears when you try to click on it. Here is the link to the menu demo: http://www.webdesignbrasov.ro/dropdown-menu/demo-menu.htm. I would greatly appreciate any tips on fixing that. I was trying z-index but no luck. Thanks.

  19. @Alex Flueras: Thanks for pointing that out. A quick inspection showed me that it was because of 2 pixel margin top value given from CSS. Here is the fixed version for both IE6 and IE7: http://jsbin.com/igivo3/2

  20. I have used it but its conflicting to other script whereas I had used yoo-aacordian/mootool library

    kindly suggest appropriate solution

  21. @Safraz – Thanks so much. It works perfect now!

  22. @pratap: Please check out this post: Using jQuery with other libraries: http://docs.jquery.com/Using_jQuery_with_Other_Libraries

  23. I like this method! It is simple to make cool dropdown menu at site!

  24. Very cool tutorial, thanks. If you want to see menus, web site trends, galleries etc, visit 1artmedia.com , you have online demo and free download. Bye!

  25. Nice, but functionality lets it down in the example

    -On RollOut the fade does not go away on 1st nav
    -when rolling from 1st nav to another 1st nav the fade out does not happen just disappears.

  26. very nice, works fine – but one last problem… the submenus wont hide when the mouse slides out to the top… or the (top) sides… see your own demo: http://www.instantshift.com/demo/dropdown_menu/
    when leaving at the top, the submenus stay…

    How to fix it? Thanks a lot!

  27. Yeah, nice post, I have learned a lot. Thanks for sharing.

  28. I also like this dropdown, but i too wonder if it’s possible to fix the issue mentioned by Florian:
    “the submenus wont hide when the mouse slides out to the top… or the (top) sides…”

  29. I’m stunning my amateur self. Have I found a solution?
    I added this code to make the submenu slide up when the mouse leaves the ul:

    $(‘#container ul’).mouseleave(function(){
    $(‘.sublinks’).slideUp(300);
    });

    … just after the slideDown-part.

  30. Wow! great technique. Thank you very much for share.

  31. Hello,

    Very good work. However there is a problem. When the “container” is put into another “div”, the drop down list goes back up again when you move the mouse over sublists. This problem only occurs in IE and not in Firefox or chrome. I am using version 8. Don’t know about previous versions. It is really frustrating. :( Any help will be really appreciated :)

  32. @ my previous post @ Subtain, I have found the solution, but its a compromise none the less. But this temporary fix will help the experienced people to help me find out the solution and not the way around. In the “ul li.sublinks a”, change the “margin-top:2px;” to “margin-top:0px;”, and the drop down list sliding back up bug will stop for IE when the “container” is inside another “div”. I am sure it is trivial issue with IE, but I really want to learn how this thing works, so please comment on my post if any of you know something about this. Thanks :)

  33. Thank you for this quick tutorial. In your html, you haven’t marked the sublinks property in the tutorial.

  34. Thanks for the menu. nice sharing!

  35. Thanks for the tutorial!

    I know it has been awhile since Florian and David were discussing the issue with the drop-down not sliding up on mouseleave, but, following David’s suggestion, I used:

    $(‘.dropdown’).mouseleave(function(){
    $(‘.sublink’).slideUp(300);
    });

    after the SlideDown bit and it is working great in IE9, FF6, and Chrome10. Hope that helps someone.

    Thanks again!

  36. So, disregard the last comment…it obviously doesn’t work. I was trying to use the classes from the example and totally got it messed up. Anyway, to get it to work I created another class for the links in my navigation that don’t include dropdown menus. That is the class that should be in my example…so something more like:

    $(’.dontdropdown’).mouseenter(function(){
    $(’.sublink’).slideUp(300);
    });

    And notice it is checking for the mouseenter event no the mouseleave…Sorry I screwed all that up. I hope this one helps!

  37. Wwow! great technique. Thank you very much for share.

  38. can u add sub sub menus which will be horizental to the submenu in this demo

  39. will be horizental to the submenu in this demo

  40. I too am interested in a sub sub menu solution. Can you please add an example? This is a great tutorial and method and I would like to stick with this concept if I can learn how to add a third tier that flies out horizontally. Thanks

  41. If i use ul list at an other place it stil get after togheter how can i set this up for only menu?

  42. Thanks a lot for sharing, Realy nice, you save my lots of time..

  43. Is there any way to add a delay on mouseleave? So that the submenu doesn’t disappear directly?
    / David

  44. I like your example. I need to do something very close to this. When you click on any of the top level navigation items, I need all the sub-items under each top level item to show. Then when you click a top level item again, I need it hide all sub-items – toggle.

    Thanks in advance for any help,

    Kay

  45. Nice clean effect, thank you. What would be the easiest way to create this same style of menu but have the sub menu slide UP above the top level items? Thanks in advance

  46. nice tutorial pls upload images

  47. Thanks a lot for this!
    It was very useful for me.

  48. Hey, Thanks Man. It surely helped a lot.

  49. This is a nice tutorial but I think a few things would make it better:

    If the menu were inside a div with a class (“menu” for example) then your styles could be written .menu ul { and could be used by people seeking to use this without modification. As it is your styles of ul and li etc will interfere with non-menu elements elsewhere in a document.

    Also Firefox no longer respects -moz-border-radius; they just use border-radius now and the latest IT also respects this.

    Thank you for posting this. It’s a fine respource!

  50. Brilliant menu. How do I change the code so the menu items ‘drop up’ above the button instead of below it. I need to place the menu at the bottom of a page and if it drops down it will vanish out of site.

    Hope you can help.

    Joe

  51. Thanks a lot.I learnt a lot about drop down menus.

  52. Nice article, but there is only one kind of menu. To make it perfectly clear, I suggest to read this article: http://basicuse.net/articles/pl/scripting_languages/javascript/jquery_for_beginners_javascript_menu here is even example when menu takes items via AJAX.

  53. Hi,
    Thanks for this nice script. It works well for me.
    I’m amateur of jQuery. Anyone could help me to add some code into $(function) in order to get the URL of when I click on menu ?
    I would like to load the page of URL and put into a .

    TIA,

  54. i like ur website and techniches

Leave a Comment Yourself

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>