Wednesday, September 30, 2009

Show and Hide Sub Menu

Currently, I have just finished my auction website project, www.allcanbid.com. That's why I didn't write for a while.
I will explain how to hide and show a sub menu.

First of all, we need the style(CSS).


/* set no underline for a tag in container class */
.container > a{
    text-decoration: none;
}

/* set display to none for a slider class in container class */
.container > .slider{
    display: none;
}



After that we need a javascript function to determine whether to show or hide the sub menu when an user click the menu.


function slide(obj){
// Check whether the obj display is none or empty
    if(document.getElementById(obj).style.display == "none")
       document.getElementById(obj).style.display = "block"; // show the sub menu
    else
        document.getElementById(obj).style.display = "none"; // hide the sub menu
}



Here is the html that is inserted in the body tag.

<div id="container_1" class="container">
    <a href="javascript:void(slide('slider_1'))">Menu 1</a>
    <div id="slider_1" class="slider">
        <div id="slider_1_1">Sub Menu 1_1</div>
        <div id="slider_1_2">Sub Menu 1_2</div>
    </div>
</div>

<div id="container_2" class="container">
    <a href="javascript:void(slide('slider_2'))">Menu 2</a>
    <div id="slider_2" class="slider">
        <div id="slider_2_1">Sub Menu 2_1</div>
        <div id="slider_2_2">Sub Menu 2_2</div>
    </div>
</div>


That's it. :-)