简体   繁体   中英

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?

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM