Jquery hide dropdown when not hovering over link or dropdown

119 Views Asked by At

This is driving me crazy.

I have a navigation and one of the items in the navigation triggers a dropdown to appear underneath the navigation when I hover over the dropdown link.

The navigation and dropdown both share the same parent.

I would like the dropdown to dissapear whenever the cursor is not on the dropdown link OR the dropdown itself. Right now the dropdown is still being shown when the cursor is inside the ul.menu

How do I fix this?

This is the JS

    $('.header_navigation a').on('mouseenter', function () {
      if (!$(this).hasClass('active_link')) {
        $('.dropdown_container').hide();
        $('.active_link').removeClass('active_link');
        $('.is-absolute').parent().addClass('feature_image');
        $('.mega-nav-desktop__blackout').removeClass('show');
      }
    });     
    
    $('.main-nav .nav, .top-bar, .cart-container').on('mouseleave', () => {
      $('.dropdown_container').hide();
      $('.active_link').removeClass('active_link');
      $('.is-absolute').parent().addClass('feature_image');
      $('body').removeClass('is-active');
      $('.mega-nav-desktop__blackout').removeClass('show');
    });

    $('.dropdown_link').on('mouseover', function () {
      $('.dropdown_container').hide();
        $('.mega-nav-desktop__blackout').addClass('show');

      const $dropdown = $(this).parents('.main-nav').find(`[data-dropdown="${$(this).data('dropdown-rel')}"]`);

      $('.active_link').removeClass('active_link');

      if (!$(this).hasClass('active_link')) {
        $dropdown.show();

        if ($(this).hasClass('mini_cart')) {
          if (!$('body').hasClass('cart')) {
            $(this).parent('.cart-container').addClass('active_link');
          }
        } else {
          $(this).addClass('active_link');
          $('.is-absolute').parent().removeClass('feature_image');
        }
      }
    });

This is the HTML

<div class="nav nav--combined nav--center">
    <ul class="menu header_navigation center">
        <li><a href="#" class="dropdown_link" data-dropdown-rel="dropdown">Dropdown</a></li>
        <li><a href="#">Nav item</a></li>
        <li><a href="#">Nav item</a></li>
        <li><a href="#">Nav item</a></li>
    </ul>
    <div class="dropdown_container mega-menu mega-menu-1" data-dropdown="dropdown">
        <div class="dropdown menu">Dropdown comes here</div>
    </div>
</div>

Jsfiddle: https://jsfiddle.net/6L1h3dr5/1/

0

There are 0 best solutions below