1

I'm trying to create a top-nav menu as follows:

enter image description here

The idea is that when you click a tab, the tab itself gets highlighted in black and an associated menu shows up beneath it. This works fine.

I also want the menu to disappear and the tab to be unhighlighted if the mouse leaves either the tab or the menu. This is where I'm running into trouble. At the moment, the JQuery I use to handle this is roughly as follows:

    $('.item-support a').click(function(e){
        // removeClass('curr') from all other tabs
            $('.item-support').addClass('curr');
            $('#submenu-support').fadeIn('fast');

            $('.item-support').mouseleave(function(e) {
                $('.item-support').removeClass('curr');
                $('#submenu-products').fadeOut('fast');

            });
        }else{ // Click again
            $('.item-support').removeClass('curr');
            $('#submenu-support').fadeOut('fast');
        }
        return false;
    });

    $('#submenu-products').mouseleave(function(e) {
            $('.item-support').removeClass('curr');
            $('#submenu-products').fadeOut('fast');
    });

    // Similar code for the other tabs

The problem is that the mouseleave events for the tab and sub-menu are not synchronized. So, for example, if the mouse leaves the support tab and enters the submenu below it, the submenu vanishes. I've tried many different approaches to get around this and even have one that crudely works using pageX and pageY co-ordinates, but I'm looking for a more elegant solution. How do I get the tab and its associated submenu to work in tandem? Is there a way to bind the two divs together? Or make mouseleave recognize an exception when entering a certain div?

José Ricardo Pla
  • 1,043
  • 10
  • 16
ericgrosse
  • 1,490
  • 20
  • 37

1 Answers1

1

You can check if either element is hovered, and do something like this:

$('.item-support, #submenu-support').mouseleave(function() {
    setTimeout(function() {
        if (!$('.item-support').is(':hover') && !$('#submenu-support').is(':hover')) {
            $('.item-support').removeClass('curr');
            $('#submenu-support').hide();
        }
    }, 50);
});

You also shouldn't bind your mouseleave event in the callback of another event. Currently every time you click item-support, you are binding another mouseleave event to it.

Tatermelon
  • 489
  • 2
  • 10
  • +1 for the idea, but now I'm having trouble with .is(':hover'). Please see https://stackoverflow.com/questions/30176517/ishover-only-working-within-a-setinterval-function – ericgrosse May 11 '15 at 19:57
  • Your solution works in Chrome but not Firefox, there seems to be an issue with .is(':hover') in firefox – ericgrosse May 11 '15 at 20:37
  • I added a short timeout to account for the strange FF behavior – Tatermelon May 11 '15 at 20:39