Jquery dropdown menu on hover or on click
children, click, drop-down-menu, hover, jquery
Solution
Try the following solutions by Directly targeting the `ul`
Solution A:
// previous (following) is very inefficient and slow:
// -- $(this).find("ul.sub-menu").not("ul.sub-menu li ul.sub-menu").slideDown();
// Rather, target the exact ULs which are Direct Children
$("ul.menu").find('li').hover(
function() {
$(this).find('> ul').slideDown();
},
function() {
$(this).find('> ul').slideUp();
// If something Slides Down, it should slide up as well,
// instead of plain hide(), your choice - :)
}
);
Solution B:
for more Precision over both ULs
Update: Solution A works fine and makes B redundant
$("ul.menu").find('> li').hover(
function() {
$(this).find('> ul').slideDown();
},
function() {
$(this).find('> ul').hide();
}
);
$("ul.sub-menu").find('> li').hover(
function() {
$(this).find('> ul').slideDown();
},
function() {
$(this).find('> ul').hide();
}
);
Check the Fiddle
Problem
I have a menu which looks like the one below. I want the first-level childs to appear on hover OR on click (so it works on iPad as well). When hovering (or clicking) a firs-level child I want it's second level childs to appear if they exist. On hover out or when clicked on a different DOM-element all submenu's should be hidden again. Also when a user is on page I want to menu to be folded out until he hovers over or clicks on a different menu item so he can always see just where he is in the navigation. I am building this in Wordpress for a friend who should be able to create and change his navigation menu using the backend. Therefore adding specific classes or ID's to some elements is not an option. ``` <style> .sub-menu {display: none;} </style> <ul class="menu"> <li>child 1 <ul class="sub-menu"> <li>child 1.1 <ul class="sub-menu"> <li>child 1.1.1</li> <li>child 1.1.2</li> </ul> </li> <li>child 1.2 <ul class="sub-menu"> <li>child 1.2.1</li> <li>child 1.2.2</li> </ul> </li> </ul> </li> <li>child 2 <ul class="sub-menu"> <li>child 2.1</li> <li>child 2.2</li> </ul> </li> </ul> ``` This is what I came up with but it does not work. When hovering over child 1.1 both 1.1 and 1.2's siblings are shown. ``` $("ul.menu li").hover(function() { $(this).find("ul.sub-menu").not("ul.sub-menu li ul.sub-menu").slideDown(); } , function() { $(this).find("ul.sub-menu").hide(); }); $("ul.menu li ul.sub-menu").hover(function() { $(this).find("ul.sub-menu").slideDown(); } , function() { $(this).find("ul.sub-menu").hide(); }); ```