Search code examples
javascriptjquerycssmegamenu

Keep a mega-menu visible until entering another anchor using jQuery


I have a menu where I would like a sub-menu to appear as long as the user is in that menu; Much like you would find in a mega-menu.

I'm using jQuery to select the elements.

This is the markup structure:

enter image description here

As you can see each <li> i.e. global-nav__list-item contains an anchor which represents an element in the main navigation.

Also nested in there is the corresponding div element i.e. collapsible__content which represents the mega-menu.

I thought this script could drill down and simply add and remove the class collapsible__content--expanded on collapsible__content which would solve my problem.

$('.global-nav__list-item').mousemove(function() {
   $(this > '.collapsible > .collapsible_content').addClass('collapsible__content--expanded');
}, function(){
   $(this > '.collapsible > .collapsible_content').removeClass('collapsible__content--expanded');
})

What am I doing wrong?


Solution

  • Firstly, your selector isn't valid. You need to use find() when attempting to select child elements from the this reference: $(this).find('.collapsible > .collapsible_content').

    Secondly, mousemove() doesn't accept multiple functions. Assuming you're expecting to add/remove the class on mouseenter/mouseleave you could use hover instead, along with toggleClass():

    $('.global-nav__list-item').hover(function() {
      $(this).find('.collapsible > .collapsible_content').toggleClass('collapsible__content--expanded');
    });
    

    Better still, you could use CSS alone to achieve this:

    .global-nav__list-item .collapsible > .collapsible-content {
      display: none;
    }
    
    .global-nav__list-item:hover .collapsible > .collapsible-content {
      display: block;
    }
    

    The above is assuming the .collapsible__content--expanded is just hiding/showing content. If not, you'd simply need to copy the relevant styles in to the above.