JQuery accordion menu

Accordion menu are a nice way to add some kind of motion to a website. This is the basic implementation of an accordion menu, without effects or other fancy stuff.

HTML markup

The HTML markup is pretty simple. We just have to define the hyerarchical structure of the menu using some lists, and add all the relevant classes that will be used later by the javascript code and the style sheet.

<div id="accordion">
<ul>
    <li class="menu">
        <div class="button">
            <a class="accordion" href="#">Section one</a>
        </div>
        <ul class="options">
            <li>
                <a class="option" href="#">topic one</a>
            </li>
            <li>
                <a class="option" href="#">topic two</a>
            </li>
            <li>
                <a class="option" href="#">topic three</a>
            </li>
        </ul>
    </li>
    <li class="menu">
        <div class="button">
            <a class="accordion" href="#">Section two</a>
        </div>
        <ul class="options">
            <li>
                <a class="option" href="#">topic one</a>
            </li>
        </ul>
    </li>
    <li class="menu">
        <div class="button">
            <a class="accordion" href="#">Section three</a>
        </div>
        <ul class="options">
            <li>
                <a class="option" href="#">topic one</a>
            </li>
            <li>
                <a class="option" href="#">topic two</a>
            </li>
        </ul>
    </li>
</ul>
</div>

Code snippet

The trick is to add or remove the relevant classes to the elements we want to show or hide.

$(function(){
    $(".options:not(:.open)").hide();
    $("a.accordion").click(function() {
        $('.active').removeClass('active')
        $(this).parent().addClass('active');
        $('.options.open').removeClass('open');
        $(this).parent().parent().children('.options').addClass('open');
        $(".options:not(:.open)").hide();
        $(".options.open").show();
    });
});

CSS snippet

And here is a touch of style.

#accordion ul {
    list-style: none;
    padding: 0;
    margin: 0;
}
#accordion li {
    list-style: none;
    margin: 1px 0;
}
#accordion a.accordion {
    background-color: #FFFFFF;
    color: #27ADD7
}
#accordion a.option {
    background-color: #FFFFFF;
    color: #27ADD7
}
#accordion .button {
    border: solid 1px #27ADD7;
    height: 30px;
    width: 150px;
    padding: 15px 0 0 30px;
    background-color: #FFFFFF;
    color: #000000;
    background-image: url('close.png');
    background-repeat: no-repeat;
    background-position: 5% 50%;
}
#accordion .active {
    background-image: url('open.png');
    background-repeat: no-repeat;
    background-position: 5% 50%;
}
#accordion .options {
    padding: 15px 0 15px 25px;
}

View demo