How can I keep my sub-menu open in jQuery hover menu?

▼魔方 西西 提交于 2019-11-29 15:13:07

I had a similar case, and solved it by splitting up the mouseover event into separate mouseenter and mouseleave events. Just pseudocode / an outline, but with your case try something like:

$("div#main-nav div").mouseenter(function() {
   // Check if sub menu is open, return if it is allready open
   // (I add a 'menu_open' class to sub menu when it is opened)

   // Code to hide open submenues
   // Code to open selected submenu      
});

Then use mouseleave and the toElement property of its event to check where the mousepointer went, if it went to a sub menu, do nothing, if not close all sub menues. Note that you need to hook up mouseleave events on the sub menues too. Something like this:

$("#main-nav div").mouseleave(function (event) {
   var toElem = $(event.toElement);
   if (toElem.closest("div.sub-nav").id=="subnav") return; // Prob nicer way to do this...point is to check if mouse enters a submenu, and if so stay open.
   // Close all open submenues, e.g. 
   $("#sub-nav ul").hide();
 });

 $("#subnav ul").mouseleave(function (event) {
    var toElem = $(event.toElement);
    if (toElem.closest("div.sub-nav").id=="subnav") return; // Check if entering submenu
    if (toElem.closest("div#main-nav")) return; // Check if entering main menu
    // Close all open submenues, e.g.
    $("#sub-nav ul").hide();
 });

Hope this is of some help to you. Just solved this myself, so haven't had time to polish it, I'm sure there are better and prettier ways to do this.

I had a similar situation, and unfortunately I wasn't able to reformat my entire menu to accommodate for the 'proper' parent/child structure.

If you simply call the sub-menu in the selector as well, it will remain 'open' during the hover state.

http://jsfiddle.net/K5P9Z/

Example -

jQuery(document).ready(function($) {

$('#kids, .menu-1').hover(function() {
    $('.menu-1').show();
}, function() {
    $('.menu-1').hide();
});
 $('#community, .menu-2').hover(function() {
    $('.menu-2').show();
}, function() {
    $('.menu-2').hide();
});
 $('#about, .menu-3').hover(function() {
    $('.menu-3').show();
}, function() {
    $('.menu-3').hide();
});

});​
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!