garethdn
garethdn

Reputation: 12351

Expand dropdown menu if one of the sub-menu items is active

I have a dropdown menu which is expanded by clicking. The menu is collapsed by default. I would like the menu to appear to be expanded if one of the sub menu pages is active. I hope that's clear. Here is my code.

HTML

<li class="dropdown">
            <a class="disablelink" href="#">Carbohydrates, proteins &amp; fats</a>
            <ul class="sub_navigation">
                <li><a href="carbohydrates.php">Carbohydrates</a></li>
                <li><a href="proteins.php">Proteins</a></li>
                <li><a href="fats.php">Fats</a></li>
            </ul>
        </li>

jQuery

$(document).ready(function() {
        $('.dropdown').click(function() {
                        // When the event is triggered, grab the current element 'this' and
                        // find it's children '.sub_navigation' and display/hide them
            $(this).find('.sub_navigation').slideToggle(); 
        });

        $(".disablelink").click(function(e) {
            e.preventDefault();
        });

    });

So if the user is on carbohydrates.php, proteins.php or fats.php i would like the menu to be expanded. I don't know how to do this though. Can anyone help?

Upvotes: 1

Views: 1614

Answers (1)

smilly92
smilly92

Reputation: 2443

When a page is active you would need to give it's link an additional class, for example;

<li class="current_page"><a href="carbohydrates.php">Carbohydrates</a></li>.

Then you can use jQuery to loop through the menu and expand it if any menu item have the class.

$('.dropdown li').each(function() {
    if ($(this).hasClass('current_page')) {
           $(this).closest('.sub_navigation').slideDown();          
    }            
});

Demo: http://jsfiddle.net/R7gkw/

Upvotes: 3

Related Questions