Thursday, June 28, 2012

Accordion menu - making a top level menu item work as a link


I was working on five-six level JQuery accordion menu to build a side navigation menu. However, i wanted to make labels with a single level menu to behave as normal links rather than the default behaviour of opening up a sub-menu on clicking the top level label.

For this, you need to capture the click event of the top level label to make it work as a normal link. Following is the solution:

The HTML code looks like:

<div id="accordion">
    <h3 class="home">
        <a href="/home" class="heading" >Home</a>
    </h3>
    <h3>
        <a href="#custom" class="heading">Custom</a>
    </h3>
    <ul>
        <li><a href="/home/mydata1">My Bio1</a></li>
        <li><a href="/home/mydata2">My Bio2</a></li>
    </ul>
  
    <h3>
        <a href="/home/Account" class="heading">Account</a>
    </h3>
    <ul>
        <li><a href="/home/avatar">Avatar</a></li>
        <li><a href="/home/Account">Account</a></li>
    </ul>
    <h3>
        <a href="#custom2" class="heading">Custom2</a>
    </h3>
    <h3>
        <a href="#custom3" class="heading">Custom3</a>
    </h3>
    <h3>
        <a href="#custom4" class="heading">Custom4</a>
    </h3>
    <h3>
        <a href="#custom5" class="heading">Custom5</a>
    </h3>      
</div>



The js code to set up Accordion with JQuery looks like:

$(document).ready(function(){
  
        $('#accordion').accordion({
                header: "h3.home",
                navigation: true,
                autoHeight: false,
                clearStyle: true,
                collapsible: true,
                alwaysOpen: true,
                animated: 'slide'
        });
       
        $('#accordion h3.home a').click(function(){
            $('#accordion a.heading').accordion("activate", -1);                                   window.location = $(this).attr('href');
            return false;
        });
});


The line: $('#accordion a.heading').accordion("activate", -1);  closes every label/header that is open.


The line: window.location = $(this).attr('href'); sets the url to navigate to, to the href value.


Creative Commons License