Wednesday, August 26, 2009

JavaScript & DHTML Dropdown Animated Menu

Menu’s are the most user friendly form of navigation technique when it comes to grouping a large number of links on your website. I have created an easy to use JavaScript/DHTML Animated Menu script which can be used without any coding required at all. Just include the JavaScript code in the header and use the menu HTML code on your page any number of times. Mouse events for opening and closing the menu’s are automatically assigned to the div tags based upon the class name. The menu rolls down slowly when mouse is rolled over it. The menu drop down speed can be controlled from the JavaScript code.

I have designed the menu with minimal amount of CSS, so you can modify the menu CSS to suit the color and styling of your website. This is how the menu would look like:JavaScript, DHTML Dropdown Menu

Here is the JavaScript code for animated dropdown menu. You can place this code inside the head section of your page or put it in a separate (.js) file and link to it. To change the opening and closing speed of the dropdown menu you can change the value for speed variable inside dropdown class. You may have to tweak around with the JavaScript code sometimes if you include borders or add extra padding to the menu class to make it work. You can adjust the menucontent.offsetHeight or total_height values by adding some number to it in the start function to make it work on your styling.

JavaScript Code:
<script type="text/javascript">
// Programmer: Abhinay Rathore
// Blog: http://web3o.blogspot.com
// Drop Down Menu Class
var dropdown =
{
      speed: 5, // Menu opening speed
      init: function() { // Initialize drop down menu
            var divs = document.getElementsByTagName("div");
            for (var i = 0; i < divs.length; i++) {
                  if (divs[i].className == "dropdown_menu"){ // attach mouse events
                        divs[i].onmouseover = function() { dropdown.start(this, 1); };
                        divs[i].onmouseout = function() { dropdown.start(this, -1); };
                  }
            }
      },
      start: function(obj, dir) {
            var menuheading = getElementChildNode(obj, 0); // Get Menu Heading
            var menucontent = getElementChildNode(obj, 1); // Get Menu Content
            var total_height = menuheading.offsetHeight + menucontent.offsetHeight + 2;
            clearTimeout(obj.Timer);
            obj.Timer = setInterval(function(){dropdown.animate(obj, menuheading.offsetHeight, total_height, dir)}, 1);
      },
      animate: function(obj, min_height, total_height, dir) {
            var objHeight = obj.offsetHeight;
            if (dir > 0){ // Expand
                  if (objHeight < total_height){
                        objHeight = objHeight + dropdown.speed;
                        obj.style.height = objHeight + "px";
                  } else { clearTimeout(obj.Timer); }
            } else if (dir < 0){ // Collapse
                  if (objHeight > min_height){
                        objHeight = objHeight - (dropdown.speed * 4);
                        if (objHeight < min_height) objHeight = min_height;
                        obj.style.height = objHeight + "px";
                  } else { clearTimeout(obj.Timer); }
            }
      }
};

// Returns Element Child node at given index
function getElementChildNode(node, index) {
      var element_node;
      var element_node_index = 0;
      var children = node.childNodes;
      for (var i = 0; i < children.length; i++) {
            if (children[i].nodeType == 1) {
                  element_node = children[i];
                  if (element_node_index == index) break;
                  else element_node_index++;
            }
      }
      return element_node;
}
// Add events
var EventUtil = {
      addHandler: function(element, type, handler) {
            if (element.addEventListener) {
                  element.addEventListener(type, handler, false);
            } else if (element.attachEvent) {
                  element.attachEvent("on" + type, handler);
            } else {
                  element["on" + type] = handler;
            }
      }
};

// Initialize dropdown menu when page loads...
EventUtil.addHandler(window, "load", dropdown.init); 
</script>

Here is the CSS style sheet for the dropdown menu, you can modify the style to suit the color and styling of your website. I have kept the z-index to 100 for the drop_down menu class to stay on top of all the contents on you page. The menu width is adjusted automatically based upon the width of the menu entry with maximum length, to keep fixed width menu you can add width attribute to the dropdown_menu and menu_heading classes in CSS or use inline styling in your HTML code.

CSS Code:
<style type="text/css">
<!--
.dropdown_menu, .menu_heading {
      height: 25px;
}
.dropdown_menu {
      overflow: hidden; z-index: 100; float: left;
}
.menu_heading {
      background-color: #033;
      border-right-width: 1px;
      border-left-width: 1px;
      border-right-style: solid;
      border-left-style: solid;
      border-right-color: #FFF;
      border-left-color: #FFF;
      cursor: default;
}
.menu_heading p{
      font-family: Verdana, Geneva, sans-serif;
      font-size: small; font-weight: bold; color: #FFF;
      margin: 0px; padding: 4px 4px 0px 4px;
}
.menu_content {
      position: relative;
}
.menu_content ul{
      margin: 0px; padding: 0px;
}
.menu_content li{
      list-style-image: none; list-style-type: none;
}
.menu_content li a{
      font-family: Verdana, Geneva, sans-serif;
      font-size: small; color: #333;
      display: block; text-decoration: none;
      cursor: default; background-color: #9CF;
      padding: 2px 4px 2px 4px;
      margin: 2px 1px 0px 1px;
}
.menu_content li a:hover{
      background-color: #E4E4E4;
}
-->
</style>

Here is the HTML Code you need to use for each Menu you want to put up on your website, the structure in pretty simple with one outside container (dropdown_menu) which contains menu heading div (menu_heading) and menu links div (menu_content) which finally contains the unordered list (ul) of links you want to put under that menu.

HTML Code:
<div class="dropdown_menu">
<div class="menu_heading"><p>Menu Heading</p></div>
<div class="menu_content">
<ul>
    <li><a href="http://www.google.com/">Google</a></li>
    <li><a href="http://www.yahoo.com/">Yahoo</a></li>
    <li><a href="http://www.msn.com/">MSN</a></li>
    <li><a href="#">My Link 2</a></li>
    <li><a href="#">My Link 1</a></li>
    <li><a href="#">My Link 2</a></li>
</ul>
</div>
</div>

To use multiple menu’s on a single page, you can create a container at top of the page to hold the menu’s and place the above given HTML Code one after the other. The dropdown menu JavaScript class’s init() functions scans all the div tags automatically and assigns mouse over and mouse out events to div tags which contain the menu class (dropdown_menu).

The only thing this menu script does not support as of now is multiple levels of cascading menu’s. I’ll work on another script soon to implement a hierarchical menu with various levels.

2 comments:

Thanks a lot for your valuable comments :)