Vian Esterhuizen
Vian Esterhuizen

Reputation: 3904

Remove hover activation on current element on click

I have a dropdown menu that works in two ways

  1. Classic CSS hover
  2. If you click the top level li it adds a class to the menu with jQuery which makes the menu show.

I have a close button in the menu to close it if you've opened the menu with a click event. I wanted to do it by removing the class on the menu. This works, except because you're still hovering over the menu the menu doesn't disappear until you hover off which isn't ideal. I also tried using .hide() but then that messes with CSS hover functionality.

Is there a way in jQuery to remove the CSS hover activation of an element? Below is how I've made it work, but I feel I can do it with less JS if I can unbind CSS hover.

    // Add class 'show' to .meganav__container. Visibility is controlled by CSS
    $('.meganav > li > a').on('click',function(){
        $('.meganav__container').removeClass('show');
        $(this).parents('li').children('.meganav__container').toggleClass('show');
    });

    // Closes menu when close button is clicked
    $('.subnav__container .close').on('click', function(){
        $(this).parents('.meganav__container').hide();
    });

    // For UX I'd like the menu to still work with hover
    $('.meganav > li').hover(
        function(){
            $(this).children('.meganav__container').show();
        },
        function(){             
            $(this).children('.meganav__container').hide();
        }
    );

This is how I would prefer it to work

// Add class 'show' to .meganav__container. Visibility is controlled by CSS
$('.meganav > li > a').on('click',function(){
    $('.meganav__container').removeClass('show');
    $(this).parents('li').children('.meganav__container').toggleClass('show');
});

// Closes menu when close button is clicked
$('.subnav__container .close').on('click', function(){        
    //Remove hover on parent li but this doesn't work
    $(this).parents('li').unbind('onmouseover').unbind('onmouseout');
    $(this).parents('.meganav__container').removeClass('show');
});

Fiddle with it

Upvotes: 1

Views: 2009

Answers (1)

Zubzob
Zubzob

Reputation: 2743

I've updated the code in this fiddle

Basically, I've made the CSS hover trigger only on a li with the class of 'hoverManagement'.

Then, we need to make sure that whenever we hover over a 'li' element belonging to the navigation ul, the class attribute gets set to 'hoverManagement', so it can trigger the CSS hover.

.meganav > li.hoverManagement:hover .meganav__container, .meganav__container.show {
    display: block;
}

For the Updated Javascript see the mentioned fiddle.

Upvotes: 1

Related Questions