mengu on web programming.

How To Make Drop Down Menus With JQuery

How Stuff Works

We see drop down menus everywhere but have you ever wondered how to make one? In this tutorial I explain how to do a simple drop down menu with jQuery.

PATH TO FOLLOW: HTML PART

What we need to create our drop down menu?

  • A div that will contain the menu.
  • A div that will contain the menu links.

So let's set the HTML part:

<style>
body
{
  background: #F9F7ED;
  font-family: Sans-serif;
}
.headerlink
{
  display: inline;
  padding-left: 15px;
}
.headerlink a { outline: none; color: #C86000; }
.hmlink { display: none; background: #FFF8DC; border: 1px solid #CCCCCC; font-size: 12px; }
.hmlink a { text-decoration: none; color: #2088B2; }
.hmlink div { padding: 5px; border-bottom: 1px solid #DADDE2; }
.hmlink div:hover { background: #DADDE2;}
</style>
<div style="margin-left: 150px;">
  <div id="hm1" class="headerlink"><a href="#">Test Menu</a></div>
  <div id="hm2" class="headerlink"><a href="#">Test Menu</a></div>
  <div id="hm3" class="headerlink"><a href="#">Test Menu</a></div>
</div>

<div id="hm1_menu" class="hmlink">
  <div><a href="#">Test Link 1</a></div>
  <div><a href="#">Test Link 2</a></div>
  <div><a href="#">Test Link 3</a></div>
</div>

<div id="hm2_menu" class="hmlink">
  <div><a href="#">Test Link 4</a></div>
  <div><a href="#">Test Link 5</a></div>
  <div><a href="#">Test Link 6</a></div>
</div>

<div id="hm3_menu" class="hmlink">
  <div><a href="#">Test Link 7</a></div>
  <div><a href="#">Test Link 8</a></div>
  <div><a href="#">Test Link 9</a></div>
</div>

Now we have written our HTML, we should write the jQuery part.

jQuery Part

  • For every div with the headerlink class, we should add a click function.
  • Get where it's positioned in the document.
  • Get its submenu id.
  • Set the submenus position.
  • Close other open submenus.
  • Make the submenu drop down.

So let's write the jQuery part.

<script type="text/javascript">
$(document).ready(function() {
  var hmIds = new Array();
  $(".headerlink").each(function(i) {
    hmIds[i] = this.id;
    $(this).click(function() {
      var offset = $(this).offset();
      var submenu = this.id+"_menu";
      jQuery.each(hmIds, function (i, val) {
        var hmsubmenu = val+"_menu";
        if (hmsubmenu != submenu) { $("#"+hmsubmenu).css('display', 'none'); }
      });
      if ($("#"+submenu).css('display') == 'none')
      {
        $("#"+submenu).css('left', offset.left+15).css('top', offset.top+17).css('position', 'absolute').slideDown('slow');
      }
      else
      {
        $("#"+submenu).css('display', 'none');
      }
      return false;    
    });
  });
});
</script>

Comments

No comments made for this post.

Leave a Response

No HTML allowed. You can use markdown.
Name*:
E-Mail* (not published):
Web site:
Response: