Wednesday, September 9, 2009

JavaScript & DHTML Accordion Menu

Accordion Menu’s are a very fancy form of drop down menu’s which are stacked over each other and open/close like the Accordion musical instrument. Reusing some of the code from my previous post on Dropdown Animated Menu, I have created a versatile and animated Accordion menu which works on both mouse over and moue down events.

Benefits of using this Accordion Menu Script:

  1. Zero coding required.
  2. Works with Mouse Over and Mouse Down events.
  3. Use multiple groups of menu’s on the same page without assigning id’s separately.
  4. Easily modifiable CSS.

This is how the Accordion Menu looks like:JavaScript & DHTML Animated Accordion Menu

The JavaScript code for this Accordion Menu is very straight forward with an Accordion Class containing all the functions. Put this JavaScript code inside the head section of your page. When the page is loaded for the first time, the init() function from the accordion class is called and all the div tags with class name accordion are assigned mouse events automatically. I have used JavaScript setTimeout function to delay the menu opening by few milliseconds so that the mouse over event can work smoothly over the menu. You can change the parameters for menu opening speed and delay inside the accordion class. To use mouse clicks for opening the menu, you can enable the onmousedown event inside the init() function of accordion class and comment the onmouseover event (no need to change the onmouseout event).

JavaScript Code:
<script type="text/javascript">
// Programmer: Abhinay Rathore
// Blog: http://web3o.blogspot.com

// Accordion Menu class
var accordions = []; // Holds objects for all the accordions on the page
var accordion =
{
    speed: 3, // Accordion opening speed
    opening_delay: 200, // Accordion opening delay in milliseconds
    run_timer: null, // Timer for active accordion
    init: function() {
        var divs = document.getElementsByTagName("div");
        var counter = 0; // Accordion Counter
        for (var i = 0; i < divs.length; i++) {
            if (divs[i].className == "accordion") {
                accordions[counter] = divs[i]; // Add to accordions array
                counter++;
                divs[i].active = 0; // Deactivate initially
                //divs[i].onmousedown = function() { accordion.activate(this); };
                divs[i].onmouseover = function() { accordion.activate(this); };
                divs[i].onmouseout = function() { clearTimeout(accordion.run_timer); };
            }
        }
    },
    closeOthers: function() { // Close all other open Accordions
        for (var i = 0; i < accordions.length; i++) {
            if (accordions[i].active == 1) {
                accordions[i].active = 0;
                accordion.start(accordions[i], -1);
            }
        }
    },
    activate: function(obj) { // Activate the accordion with opening_delay timer
        accordion.run_timer = setTimeout(function() { accordion.start(obj, 1) }, accordion.opening_delay);
    },
    start: function(obj, dir) { // Start opening Accordion
        accordion.closeOthers(); // Close all open Accordions
        obj.active = 1; // Activate the current one
        var accordion_heading = getElementChildNode(obj, 0);
        var accordion_links = getElementChildNode(obj, 1);
        var total_height = accordion_heading.offsetHeight + accordion_links.offsetHeight + 2;
        clearTimeout(obj.Timer);
        obj.Timer = setInterval(function() { accordion.animate(obj, accordion_heading.offsetHeight - 1, 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 + accordion.speed;
                obj.style.height = objHeight + "px";
            } else { clearTimeout(obj.Timer); }
        } else if (dir < 0) { // Collapse
            if (objHeight > min_height) {
                objHeight = objHeight - (accordion.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 Accordion menu when page loads...
EventUtil.addHandler(window, "load", accordion.init); 
</script>

The CSS for this menu script is kept very simple so that you can modify it to match the color and styling of your website. The most important thing you might have to change according to your website dimensions is the width and height of main accordion div and accordion heading div which can be done in the first group under CSS styling:

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

The HTML Code for Accordion Menu is pretty straight forward with a main container (accordion) which contains heading div (accordion_heading) and a links div (accordion_links) which contains an unordered list of links under the menu. Do not disturb the inner structure of the Accordion DOM layout or else you will have to modify the JavaScript to work with it as well. You can place the same code multiple times to create a group of menu’s stacked upon each other. The accordion div tag is left floated so you can use a main container on the left or right side on your website and place this HTML code in there multiple times.

HTML Code:
<div class="accordion">
<div class="accordion_heading"><p>Accordion Heading</p></div>
<div class="accordion_links">
<ul>
    <li><a href="#">My Homepage</a></li>
    <li><a href="#">My Blog</a></li>
    <li><a href="#">Favorite Video's</a></li>
    <li><a href="#">Favorite Music</a></li>
    <li><a href="#">My Link 1</a></li>
    <li><a href="#">My Link 2</a></li>
</ul>
</div>
</div>

del.icio.us Tags: ,,

No comments:

Post a Comment

Thanks a lot for your valuable comments :)