Drop Down Menu Using Javascript and CSS

Having a drop down menu on your site header will help your visitors a lot to navigate your site, especially one with a lot of pages. This is an example on how to create a drop down menu on your website using a simple Javascript. Please note that this would not work if your visitor deactivates the Javascript function on their browser. Let’s get started.

Javascript

First of all, we need to add the Javascript function into the page. Copy and paste the code below, the head section of your page will be a great place, but you can paste them into the body section as well.

<script type="text/javascript">
// Function to activate the drop down menu
function dropdown(labelid) {
  var label = document.getElementById(labelid);
  if(!label) return true;
  if(label.style.display == 'none') { label.style.display = '' }
  else { label.style.display = 'none' }
  return true;
}
</script>

Writing the Menu

Now we need to create the menu. Here’s the example;

<div class="menu">
  <ul>
    <li onmouseover="dropdown('droplist');" onmouseout="dropdown('droplist');" >
      <a href="#">Menu Example</a>
        <ul id="droplist" style="display: none;">
        <li><a href="#">Dropdown menu Example : Line 1</a></li>
        <li><a href="#">Dropdown menu Example : Line 2</a></li>
        </ul>
     </li>
   </ul>
</div>

Styling The Menu Using CSS

Then we need to style the menu using CSS to make the drop down function work. Here’s the example.

/* Style for the main menu */
.menu { z-index: 100; margin: 0; font: 11px Verdana; }
.menu ul { list-style: none; margin: 0; padding: 0;  }
.menu ul li { position: relative; float: left; border: 1px solid #000000; }
.menu ul li a { display: block; padding: 0 5px; margin: 0; text-decoration: none; cursor: pointer; height: 25px; line-height: 25px;  }
.menu ul li a:hover { background: #336699; color: #ffffff; }

/* Style for the sub-menu (dropdown) */
.menu ul ul { position:absolute; top: 25px; left: -1px; padding-top: -1px; border-top: 1px solid #000000; }
.menu ul ul li { display: block; border-top: 0; }
.menu ul ul li a { line-height: 25px; padding: 0 5px; margin: 0; text-decoration: none; cursor: pointer; width: 200px; }
.menu ul ul li a:hover { background: #336699; color: #ffffff; }

You will want to style the menu to match your page such as colors, border and font. To do that, please note that changing to the styling code might affect the result.

9 comments on "Drop Down Menu Using Javascript and CSS"
1 trackback
  1. [...] menu.. Ini nyomotnya sih dari blog orang (I’m not a designer you know!!!). Nyomotnya sih dari sini. Cara simple sih gini, kita buat dulu script javascriptnya. Entah itu di file terpisah atau di buat [...]

Leave a Response