-2

I have a menu with parent and child elements. If you hover over a parent item with children, the submenu slides down. If you hover off, it slides up. Perfect.

However, if you are ON a child page, how do I change this jquery to have that submenu open by default?

So if an item has the class "current_page_ancestor" it would be open on page load

jQuery(function($) {
$('.side-menu ul > li, ul.children > li, .side-menu ul > li, ul.sub-menu > li').hover(function () {
if ($('> ul.children, > ul.sub-menu',this).length > 0) {
    $('> ul.children, > ul.sub-menu',this).stop().slideDown('slow');
}
},function () {
    if ($('> ul.children, > ul.sub-menu',this).length > 0) {
        $('> ul.children, > ul.sub-menu',this).stop().slideUp('slow');
    }
});

});

http://jsfiddle.net/9s32z8hy/

Lumi Lu
  • 3,289
  • 1
  • 11
  • 21
joshdfw
  • 41
  • 1
  • 6
  • How are you going to identify you're on a child page? Unless child pages have a class only found on them, you really can't persist with Javascript. – Waxi Jan 28 '15 at 22:28

1 Answers1

0

You could make your code a bit more modular by creating functions to open and close the menu items. Then you can check on the page load if there's a li element with class current_page_ancestor and use a function to open it:

jQuery(function ($) {
    $('.side-menu ul > li, ul.children > li, .side-menu ul > li, ul.sub-menu > li').hover(function () {
        if ($('> ul.children, > ul.sub-menu', this).length > 0) {
            slideOpen(this);
        }
    }, function () {
        if ($('> ul.children, > ul.sub-menu', this).length > 0) {
            slideClose(this);
        }
    });

    if ($('li').hasClass('current_page_ancestor')) {
        slideOpen('.current_page_ancestor');
    }
});

function slideOpen(item) {
    $('> ul.children, > ul.sub-menu', item).stop().slideDown('slow');
}

function slideClose(item) {
    $('> ul.children, > ul.sub-menu', item).stop().slideUp('slow');
}

Fiddle: http://jsfiddle.net/9s32z8hy/2/

balzafin
  • 1,416
  • 1
  • 17
  • 28