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: ,,

5 comments:

  1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Front end developer learn from Javascript Training in Chennai . or Javascript Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry. ES6 Training in Chennai

    ReplyDelete
  2. mytectra placement Portal is a Web based portal brings Potentials Employers and myTectra Candidates on a common platform for placement assistance.

    ReplyDelete
  3. Guaranteed #1 Search Engine Ranking Supreme Free Viral Traffic Join Now Get Millions Of Hits Free To Your Site/Blog!

    PornKings Adult Shopping Backlinks-Shopping Mega Store Legendary Stars As Stormy Daniels,Shawna Edwards,Jenna Jamison-New Adult Stars Movies,Adult Toys,Enhancers,Merchandise-More !

    Hits Express Rotator System Do You Need Visitors to Your Website or Affiliate Program? If your looking to gain more visitors to your website Hits Express is your answer. With our program your site is being shown to people all over the world 24/7 365 days a year!

    PAYDIR Free For All Forum Portal Search Engine Crawled Network PR10 Ranking Information Forum XXX!

    FreeLinkExchanges Be Seen In 12 Nations 312 Sites Over 30 Millions Viewers Monthly Buy Featured Link Now With 150 Search Engines Crawling The Network!

    How do I get guaranteed traffic? When someone signs up from your site, they must first click on your classified ad which will open a new window leading to your main website. They will have to wait a few seconds for the code to appear on a separate frame at the top of the screen reach millions free now!

    Blast Your Ad to Over 23,000 Opt-in Prospects at ShowMyLinks Submit Your Solo Email Ad to All Showmylinks Members GET YOUR TEXT LINK ADs LISTED 100% FREE FOR LIFE PLUS EARN MONEY TO YOUR PAYPAL!!

    Adult Store Empires Backlinks Resources Search Engine XXX!

    GET YOUR OWN MONEY-MAKING AD BOARD -- Integrating Text ad, Banner Ad and Email Ad into one Portal Make Money Fast With Your Paypal Reach Million Dollars In A Year Fast !

    Full Length Homemade Videos Watch real people's private home sex videos. Forget about those shitty 1-2 minute clips, these are all high quality full length videos! 40+ Bonus Sites You will also get full access to the entire reelpass network of sites which features over 40+ awesome movie sites, 1000's of movies and pictures to download! Download, Burn & Share Not only do you get to watch all our movies, you can also download every single one and save it forever, burn them to dvd or share with friends!!

    ReplyDelete

Thanks a lot for your valuable comments :)