Building An Expanding DHTML Menu With CSS and JavaScript

Introduction

Today I am going to show you the different parts that make up a dropdown vertical menu for your website. This is not like your normal dropdown menu, which appears at the top of your content, however — these menus expand and remain visible until they are collapsed with the click of a mouse. The menu content actually expands with your page content, pushing the rest of whatever is below it down – so it can actually be used for more than just a menu (I might explore that a little later in another tutorial).

For now, let’s get it started…

What does the finished menu look like and how does it function?

Here’s a snapshot of what the menu looks like all coded up.

When you click on one of the links ie. Menu 1, Menu 2, Menu 3, Menu 4, Menu 5, this will expand or contract the submenu for that menu item. Basically, the end user must have JavaScript enabled to allow the submenus to work.

Let’s build the menu html

First I’m going to start with the 5 menus items. Here’s the code that I’m using, which is very simple; 5 hyperlinks. I will need to apply a style to these level one links, so I will make a class style called “menu1″.

<a class=”menu1″>Menu 1</a>
<a class=”menu1″>Menu 2 </a>
<a class=”menu1″>Menu 3 </a>
<a class=”menu1″>Menu 4 </a>
<a class=”menu1″>Menu 5 </a>

Now I will create the menu1 class style and put it in the head of my document. So far we haven’t done anying revolutionary. I won’t explain the style that I’ve applied here because it’s pretty straight forward – it’s just a background image and the display:block makes it display like a rectangle.

<style type=”text/css”>
.menu1{
background-image:url(images/menudiv1bg.gif);
margin-left:25px;
padding-left:20px;
padding-top:2px;
padding-bottom: 2px;
display:block;
text-decoration: none;
color: #000000;
height: 20px;
}
</style>

Now I’ll add the sub menus in place exactly where they will appear. In this part, we will use some small tricks to setup the alignment. Firstly, we’ll wrap the whole submenu in a div that has a unique id for each menu. You can choose your own names for the div tags, but the main purpose of the div having a unique id is so that JavaScript can target that div specifically and make it appear or disappear. I also add a class style called ‘hide’ so that I can choose to hide all of the submenus from within my style sheet. The links are then listed within the div just like the main menu items and are given a submenu class style, to allow me to control the look of those in my style sheet as well:

<a class=”menu1″ >Menu 1</a>
    <div id=”mymenu1″ class=”hide”>
        <a href=”#” class=”submenu”>Link One here</a>
        <a href=”#” class=”submenu”>Link Two here</a>
        <a href=”#” class=”submenu”>Link Three here</a>
        <a href=”#” class=”submenu”>Link Four here</a>
    </div>
<a class=”menu1″>Menu 2 </a>
    <div id=”mymenu2″ class=”hide”>
        <a href=”#” class=”submenu”>Link One here</a>
        <a href=”#” class=”submenu”>Link Two here</a>
        <a href=”#” class=”submenu”>Link Three here</a>
        <a href=”#” class=”submenu”>Link Four here</a>
    </div>
<a class=”menu1″>Menu 3 </a>
    <div id=”mymenu3″ class=”hide”>
        <a href=”#” class=”submenu”>Link One here</a>
        <a href=”#” class=”submenu”>Link Two here</a>
        <a href=”#” class=”submenu”>Link Three here</a>
        <a href=”#” class=”submenu”>Link Four here</a>
    </div>
<a class=”menu1″>Menu 4 </a>
    <div id=”mymenu4″ class=”hide”>
        <a href=”#” class=”submenu”>Link One here</a>
        <a href=”#” class=”submenu”>Link Two here</a>
        <a href=”#” class=”submenu”>Link Three here</a>
        <a href=”#” class=”submenu”>Link Four here</a>
    </div>
<a class=”menu1″>Menu 5 </a>
    <div id=”mymenu5″ class=”hide”>
        <a href=”#” class=”submenu”>Link One here</a>
        <a href=”#” class=”submenu”>Link Two here</a>
        <a href=”#” class=”submenu”>Link Three here</a>
        <a href=”#” class=”submenu”>Link Four here</a>
    </div>

I’ll add the submenu and the ‘hide’ style to my style sheet now:

.submenu{
background-image: url(images/submenu.gif);
display: block;
height: 19px;
margin-left: 38px;
padding-top: 2px;
padding-left: 7px;
color: #333333;
}

.hide{
display: none;
}

I’ll also create the style that will show the hidden div tags (submenus):

.show{
display: block;
}

Creating the JavaScript

If you’re not too familiar with JavaScript or are in a rush, feel free to just copy and paste the code shown below into your page header as is. There are no further tricky parts to setup as the JavaScript simply compares the current state of the chosen submenu and then swaps it, meaning that if it’s hidden, then it will be made visible, and vice versa.

Here’s the code:

 
<script language=”JavaScript” type=”text/JavaScript”>
<!–
menu_status = new Array();

function showHide(theid){
    if (document.getElementById) {
    var switch_id = document.getElementById(theid);

        if(menu_status[theid] != ‘show’) {
           switch_id.className = ‘show’;
           menu_status[theid] = ‘show’;
        }else{
           switch_id.className = ‘hide’;
           menu_status[theid] = ‘hide’;
        }
    }
}

//–>
</script>

Place this code in the <head> part of your web page. Next, I’m inserting the o
nClick event to the main menu links to call the showHide function when you click on the link:

<a class=”menu1″ onclick=”showHide(‘mymenu1′)”>Menu 1</a>
    <div id=”mymenu1″ class=”hide”>
        <a href=”#” class=”submenu”>Link One here</a>
        <a href=”#” class=”submenu”>Link Two here</a>
        <a href=”#” class=”submenu”>Link Three here</a>
        <a href=”#” class=”submenu”>Link Four here</a>
    </div>
<a class=”menu1″ onclick=”showHide(‘mymenu2′)”>Menu 2 </a>
    <div id=”mymenu2″ class=”hide”>
        <a href=”#” class=”submenu”>Link One here</a>
        <a href=”#” class=”submenu”>Link Two here</a>
        <a href=”#” class=”submenu”>Link Three here</a>
        <a href=”#” class=”submenu”>Link Four here</a>
    </div>
<a class=”menu1″ onclick=”showHide(‘mymenu3′)”>Menu 3 </a>
    <div id=”mymenu3″ class=”hide”>
        <a href=”#” class=”submenu”>Link One here</a>
        <a href=”#” class=”submenu”>Link Two here</a>
        <a href=”#” class=”submenu”>Link Three here</a>
        <a href=”#” class=”submenu”>Link Four here</a>
    </div>
<a class=”menu1″ onclick=”showHide(‘mymenu4′)”>Menu 4 </a>
    <div id=”mymenu4″ class=”hide”>
        <a href=”#” class=”submenu”>Link One here</a>
        <a href=”#” class=”submenu”>Link Two here</a>
        <a href=”#” class=”submenu”>Link Three here</a>
        <a href=”#” class=”submenu”>Link Four here</a>
    </div>
<a class=”menu1″ onclick=”showHide(‘mymenu5′)”>Menu 5 </a>
    <div id=”mymenu5″ class=”hide”>
        <a href=”#” class=”submenu”>Link One here</a>
        <a href=”#” class=”submenu”>Link Two here</a>
        <a href=”#” class=”submenu”>Link Three here</a>
        <a href=”#” class=”submenu”>Link Four here</a>
    </div>

Some Geek Speak, for those who just want to know what’s happening in the code.

Ok. What’s happening here is that when the page loads, the JavaScript and CSS styles in the head will load first and then your menu links will appear in the body of the page. JavaScript is loaded from top to bottom by the browser, so let’s read from inside the script tags:

The menu_status = new Array(); line will create a container ready to store the current state of your menu. This corresponds to the sections of the code that actually say what this menu_status now equals. eg. menu_status = ‘show’; and menu_status = ‘hide’;

There’s a function called showHide(theid) but this won’t do anything unless it is called from within your HTML code. ‘theid’ is the id of the menu being shown or hidden, and it’s called during the onClick even of that menu, such as onclick=”showHide(‘mymenu5′)”.

Ok, so the function loads ready to be used, but the page continues to load…

Your main links and submenus load, but only the main links show because the ‘hide’ style that’s applied to the submenus will hide the submenus. The submenus have in fact loaded already, they just aren’t showing just yet.

If you click on a main menu link, then here’s what happens:
 

  • The onClick event will fire up the showHide function and JavaScript will know which object we are working with by the id of the link.
  • JavaScript will get the menu element in question by the id that’s passed to the function
  • JavaScript now has to check whether the current menu_status is visible or not, and then swap it. If it’s not ‘show’ eg. if(menu_status[theid] != ‘show’) then the status_id will be made to equal ‘show’. If it’s not hide, eg. if(menu_status[theid] != ‘hide’) then it will be made to equal ‘hide’.

Conclusion
In this article I’ve shown you how to build a basic vertical drop down menu using DHTML and JavaScript. This is a groovy little script that will allow you to create a nice menu, or even save you some space if you currently have multi level menus laid out on your site. You can probably do more with this script if you’re familiar with JavaScript or don’t mind experimenting, but we’ll leave it at that for now!

This entry was posted in Featured, Programming. Bookmark the permalink.

90 Responses to “Building An Expanding DHTML Menu With CSS and JavaScript”

  1. Jennifer says:

    This is excellent! Thank you very much! Your tutorial of an expanding menu was just about the only one that I understood, and wasn't needlessly complicated. It is also very cross-platform, which isn't something I can say for some of the others I've run across. I will definetely reccomend your tutorial(s) to others when asked. Linked in my favorites and from my website.

    Thank you again,
    Jennifer

  2. Anonymous says:

    Thanks for the help, it actually worked!

    [ Editors note: Really? It worked? Funny that :) ]

  3. Tari says:

    Yay! Thank you so much! It's exactly what I was looking for. I'd found a way over complicated version that didn't work with 3 layers cause you could only have one menu open and I couldn't work out how to stop that. But this is perfect! Such simple coding too, I think I may learn it _

  4. Ronald Weller says:

    Yeah just what I needed. And similar to comment #2 I´ve been searching the net over and over for a simple and flexible "3-layer-expanding-menu" et voilá I found it here. And last but not least I understood what I did. Thanks to you.

  5. Neil says:

    Nice. but the cursor des not change on mouse over like it would fr a normal button. It will through some people i am sure

  6. Fabian H says:

    Excellent article. simple & powerful.
    Although I would like to get the background images used inside the CSS code in order to get the exact appeal of the example image. It looks wonderful!

  7. Aaron says:

    Very simplified article… good to see someone get it right. I would like to learn how to add persistent states to this function. I'm sure it would be as simple as adding a cookie function into the .js, I guess that's the next tutorial I'm looking for.

  8. Iona says:

    Excellent, thank you so much, this is simple, elegant and it works. Some info on creating persistant states would be very useful. Thanks again.

  9. isobar says:

    Very nice! I modified the script slightly to hide sub-menus for non-clicked items;

    The Javascript:
    function showHide(theidPrefix, theidNum)

    // show/hide clicked menu element
    if (document.getElementById)
    var switch_id = document.getElementById(theidPrefixtheidNum);

    if(menu_statustheidPrefixtheidNum != 'show')
    switch_id.className = 'show';
    menu_statustheidPrefixtheidNum = 'show';
    else
    switch_id.className = 'hide';
    menu_statustheidPrefixtheidNum = 'hide';

    // hide non-clicked menu elements
    n = 1;
    while( document.getElementById(theidPrefixn) )
    if(n !== theidNum)
    var hide_id = document.getElementById(theidPrefixn);
    hide_id.className = 'hide';
    menu_statustheidPrefixn = 'hide';

    n;

    To use it, the onclick function call on your links is modified to be:
    onclick="showHide('mymenu', 2)"

    The <div> IDs stay the same, ie "mymenu1", "mymenu2", etc.

    • Lekan says:

      thks for a great update to the script. I don’t know javascript and was trying to use the updated script:

      Do you know why it is not working?

  10. Jerry says:

    I liked how the geek speak was at the bottom. I am just an 18-yr-old interested in computers and I learned html and am beginning javascript. Your methods were new to my experience and interesting to peruse.

  11. mete kamil says:

    very nice! i will be sure to use! :-)

  12. Vishal says:

    yeap, this is good stuff, but a little of putting the menus in persistent state would make this script even better, hope someone is working on the persistent method.

  13. chili says:

    this is great! It took me long time to find such a useful and simple solution to create a nice menu!

  14. Josh says:

    Great tutorial, very easy to understand. I am also looking for a persistent state of this. Also for teh person that suggested putting in href="javascript:?" in the link to create the normal mouseover action works but creates an error on the page. Anyone know a way to remove this error?

  15. UltimaniumX says:

    To fix the error with making the menus have a "click cursor", instead of typing href="javascript:?", type href="javascript:;". That way, the actual javascript will run normally, even though there is nothing to run in the script.

  16. Joel says:

    Thanks a lot! This is exactly what I've been looking for

  17. Brad says:

    This was very helpful – thanks!!!

  18. Lucia says:

    Thank You so much … I've been looking for this for ages, never found a script for this half as good or half as clean… Thanks again!

  19. Faz Raja says:

    Excellent! I was browsing the net for a while and all the tutorials were so difficult to understand.This was so easy to understand.Nice Job!!

  20. satyanarayana Murthy says:

    Good ones indeed….
    Regards
    Satya

  21. Doug Lawrence says:

    I've looked at many and this is the best and cleanest one.

  22. Jennifer Perez says:

    Excellent article…to the point and complete…Loved it.

  23. jocelyn says:

    thank you so much for this code! I'm 13, and even I understand it! just what I was looking for :

  24. Krishnasamy Sadasivam says:

    This is excellent!! Thank you so much !!

  25. russ says:

    finally something thats easy to understand, excellent tut thanks for sharing your knowledge

  26. Alex says:

    This was an amzazing tutorial thank you so much. One question though, how do you make the menu open when you just roll your mouse over? Please edit my comment and give me the code. Thanks.

  27. Roopa says:

    Great job. THank you very much!!

  28. Dave says:

    A good example and explained well. I suggest that you only need to query the current classname of the object and switch it between hide/show. Also you can collapse the last one expanded by keeping the name of the last expanded one.

    <script>

    var last_expanded = '';

    function showHide(id)
    {
    var obj = document.getElementById(id);

    var status = obj.className;

    if (status == 'hide') {

    if (last_expanded != '') {
    var last_obj = document.getElementById(last_expanded);
    last_obj.className = 'hide';
    }

    obj.className = 'show';

    last_expanded = id;
    } else {
    obj.className = 'hide';
    }
    }

    </script>

  29. chitra says:

    thanks, that's exactly what i was looking for. if it worked for me i'll be able to make good presentation, thanks once again

  30. Juha Nyman says:

    Thank you! This is everything I have needed!

  31. martin says:

    how much of a geek does jerry at comment #7 sound. Jerry if your reading there's something you can gert to help your coding its called a life get out more and chase girls. Incidentally tutorial looks great just what I've been falling asleep looking for, for the last 20 mins

  32. Arun says:

    Thanks!! This is exactly what I was looking for!!!

  33. dane says:

    It is simple to understand and encouraging to learn new things. One thing I couln't get the background image covers the whole page . how do youmake it so that it didn't pass the menu boundry.thanx

  34. J BIzzle says:

    If everyone had tutorials like this!

  35. Nick says:

    Thanks this is great – and the extra JS script from Dave helped out a lot.

  36. Fskhan says:

    Great tutorial GREAT ;)

  37. ronnie says:

    very nice and thanks to dave aswell

  38. Victoria says:

    Excellent ! Just what I wanted – and easy to use.

  39. Jet says:

    My goodness, if what all the comments
    say are true, the author must be a heck
    of a writer. He could be a new Dan Brown
    if he switches to fiction writing. So,
    to give due credit, congrats to the author.

  40. Reza says:

    Thank You Dave.
    Very Useful.

  41. Chris says:

    Nice one. That puts a solid foothold in my slippery css learning curve.

  42. CoolDudeBudMan says:

    Re: comment #26
    Use href="#" instead of href="javascript:?"

  43. Jesse says:

    Yes, very good work. I'd agree with others that state that it's a simple, straightforward and cross-platform menu, plus – it's described in a way that's easy to dissect and understand.

  44. Sam says:

    Well written, clean and elegang – thanks!

  45. Richard says:

    How do I keep the menu open on the current page within a section?

    Hope someone can help…

    Cheers,
    Great tut!

  46. J says:

    Great Work. It really helped me out!

  47. Vimala says:

    Excellent. It is exactly the answer for my problem and it is very simple to understand. Thank you.

  48. Saqib says:

    Very nice.

    Its very simple to make and learn. Thank you very much

    Saqib

  49. Nishat says:

    good explain of how to work!

  50. Damian says:

    Is there a way to save the menus current state? Can anyone help with this please. If I refresh the menu it doesn't stay where I last clicked…
    Thanks

  51. sonal says:

    thanks. it helped me out!! I am looking for tabbed menu similar to this, any help?

  52. Carol Champion says:

    Thanks! This works really great. I used post #19 suggestion. Only problem is in Firefox it does not go as a list & is all over the place. Any way to solve this?

  53. Robert says:

    Where can I download the two image required for this tutorial, menudiv1bg.gif & submenu.gif?

  54. ian says:

    Brilliant, just what I was looking for with the mod of Dave's post (#19). My own modification – to make your mouse appear as a HAND when you go over the links you can use this:

    a{cursor: hand}

    in your styles

  55. TEMPLATE MAN says:

    this is far the easiest and most explanatory tutorial for us non web savy beginners, thank you for this and i hope there will be more tutorials on this.

  56. Dongan says:

    Hi,

    thanks for very simple, nice article.

    is there any options when the sub menus are active, the main menu should be expanded automatically?

    Thanks.

  57. One Time says:

    Well, it's a good code and all, but I find one problem in it: If you copy and paste the exact code, then when you click ANYWHERE which horizontally leads to the line, it makes the menu drop down. It's not just clicking the letters themselves, but clicking the whole line of the letters.

  58. VINIT PRATAP SINGH says:

    Thanks a lot… its very nice…

  59. Robert says:

    What CSS font-family is being used?

  60. Sara says:

    Thank you, this is amazing and exactly what I have been looking for to add to my site! It is easy to follow and even easier to apply to an already pre-made site. I dont know JavaScript at all, but I was still able to use this. Thanks so much =)

  61. Lilly says:

    Great menu: Can anyone tell me how I can make Level 1 items a link themselves? ie. When I add an href or Goto it breaks the drop down functionality attached to it. Cheers and thanks!

  62. Daniel says:

    This is the best tutorial I've found. The code is simple, and easy to understand without extra, fussy details that block the true nature of the code. In 28 lines of CLEAN CODE, you've done better than what others couldn't do in more than 40 lines of TRERRIBLE code.

  63. Jill says:

    This is excellent! Anyone know how to make the submenus stay visible after clicking on the main menu links?

  64. aileen says:

    anybody know how to add "memory" so that links stay open when page is changed? I really need this function, but this tutorial is awesome for a basic menu.

  65. Noushath says:

    Really super logic and simple too. HElped me a lot in understanding the logic of menu

  66. Mre says:

    Hi what would i need to do to add sub menu's to the sub menu's?
    i.e another teir of submenus. e.g heading of "tools" that opens "spanners"
    that opens sub menu's of "ring spanners" and "open end spanners" etc.

  67. Aiddis says:

    Interesting article.

  68. cardinal says:

    forgive my ignorance, but when i view this in ie, i have the following issue. i have placed text to the right of the menu. when i select a menu item the text stays in place, but it is indented to the right as the menu expands. is there an ie fix for this? any help is appreciated.

  69. Duncat says:

    That is the easiest widget of this type I have seen. I would like to persist this state so that if the same menu opens on a different html page, it would remember whether it was open or closed. Would I do that by passing it through a querystring, then checking for the querystring on the page load? Sorry, not so good with javascript. And that's why I'm very thankful for this, Joseph!

  70. Dana says:

    Excellent. And very easy to implement, too !

  71. Michele says:

    Great tutorial, but like mentioned by other people before, it would be just so much greater if it included some optional code snipets for things like
    Expand just one menu at a time (i.e. Menu1 closes when I open Menu2)
    Retain memory of which submenu is open (i.e. when I click Link1, Menu1 submenu will remain open)
    How to add links to main menu items without losing submenu functionality (i.e. when I click on Menu1 I am taken to a Menu1 overview page, but Submenu1 still opens).
    If anybody knows how to do this and posted the code, I'm sure lots of people would be eternally grateful (including myself)!

  72. Don says:

    Great tutorial! How about a horizontal menu with this layout. Or how to make this a horizontal menu?

  73. Ted says:

    Awesome script. Between your step-by-step guide and the comments here, it was exactly what I was looking for.

  74. Muhammad azee says:

    Congratulation for simplifying what many have presented as a nightmare. Thanks a lot

  75. rajkiran says:

    it's really nice but its not really user convenent if u see the site menu
    that every menu before this menu are very sensitive like onmouseover when we keep mouse on that it automatically show the submenu and u told that its space saving but i don't think so because when we click on menu it will open and take more space than other menu other menu only show the submenu and automatically close when we simply keep our mouse far from that but here we have to again click on menu1 and than it close the submenu.
    still i feel its nice why i don't know…….

  76. Kamthan says:

    Great scripting. I had never seen such a simple demonstration on creating a menu. Thanx for Tutorial..

  77. Tim Daniels says:

    A fantastic menu which I've put to great use in our Community Centre's Web site in Melbourne. Very easy to understand and customise!
    A thousand thank you's!!!

  78. indnajns says:

    What are the menu_status lines for? Remove them and the code works for multiple levels and is much cleaner.

  79. Anand says:

    This is good for lay man like me. You explained in a nice way that I could understand the css and javascript code.

  80. Rene says:

    This was great help for what I am trying to achieve. I see a number of people posting here have asked for instructions on adding another level of sub-menus to sub-menu items. I was able to do this (parent > child > child) by adding a .subsubmenu class and a set of mysubmenu divs and calling them where appropriate in the menu. I've also added the cursor instruction so that the pointer is a hand, as per comment #57 by Ian. Dave's instructions (#18) got me part way to the next level of functionality I was after: previously expanded main menu item collapses when a different main menu item is clicked, so that only one main menu item is expanded at a time. Thanks Dave! I have one issue with it though: I need this to be ignored when it's a sub-menu that has another set of sub-sub-menu items to be displayed. I suppose that will be another "if" statement in Dave's script. Dave, are you out there?

    Another question asked several times but unanswered is how to make the current state of the menu remain intact when a sub-menu item is clicked and the visitor is taken to the linked page. This is akin to cheating, but how I plan to do this is to create a different menu for each main menu item's related pages. In each of these menus I will change the "hide" state to "show" so that they match what main menu item was expanded when they clicked to that page. I will use server side includes to call up the appropriate menu. It would be nicer to build the functionality into one menu, but this should work. It won't actually be "retaining" its state, but on each sub page it will display the way it was when the visitor clicked something.

  81. Rene says:

    Great stuff. In comment #18 Dave provides the code to designate that only one menu item is expanded at a time. Now, I'd like to know how to tweak that so that when a sub menu has another level (sub sub menu) that function is ignored. The way it is now, when I click on my sub menu item, it's parent menu collapses.

  82. Paul. says:

    Thanks, you're a legend! And thanks to those who posted the extra bit of script to modify it that helped me loads!

  83. Shan says:

    Thanks this was a great way to build an expanding window. I needed one for dotnetnuke and this was awesome. W3C compliant as well, awesome. Cheers!

  84. Rowno says:

    This is awesome! I’ve been trying to learn javascript to make a drop down menu but it’s just too hard for me (PHP and HTML is alot easier :P ).

    I changed the onClick to onMouseOver and onMouseOut to make the menu open without having to click it and I’m going to try to arrange them out in a line to make it a drop down menu.

    Thanks alot for making this code, it will greatly improve my future websites. :D

  85. Randy says:

    It doesn’t get any eaiser than this. So simple and clean. Many, many thanks to the original author and Dave!

  86. Ashish says:

    very nice, simple and pleasant article for the beginner’s like me
    very nice work…….thnx a lot :)

  87. Luke says:

    Awesome tutorial! I’ve been searching for a few hours for how to do this and this is the only page I found that is exactly what I needed. Thanks a lot!

  88. Richard says:

    Hi,

    To be honest, I was very disappointed with the Menu system.

    I would have thought that given it was a shopping cart and potentially a large menu range, that the developers would have employed a collapsable menu system by default?

    The problem with this suggested menu script is what happens if the user has Java turned off?…

Leave a Reply