Skip to content Skip to sidebar Skip to footer

Jquery Toggleclass Conflict

For a new webdesign I have two 50% width slider div's as a menu, and I want to add/remove/toggle the 'open' class with jQuery. On the click of one of the .menul, the #left should h

Solution 1:

I had another look and you will have to add another class or data attribute to differentiate between an active-and-closed menu and a active-and-open menu or this won't work.

The active "flag" is to ensure you only toggle the .open class on an active menu.

In addition you also need to keep unbinding the hover event as otherwise you are constantly re-binding the hover, causing the element to have multiple hover events bound which then will all execute and contradict each other.

Note that when unbinding the hover event using jQuery off('hover')/unbind('hover') doesn't work and you must unbind the mouseenter and mouseleave events as those are bound by jQuery when using selector.hover(...)

The new JavaScript code is as follows:

$('.menul').click(function () {    
    $('#left').addClass('active');
    $('#left').addClass('open');
    $('#right').removeClass('active');

    $('#right').off('mouseenter mouseleave').hover(function(){
        if($('#left').hasClass('active')){
            $('#left').toggleClass('open');
        }
    });
});

$('.menur').click(function () {
    $('#right').addClass('active');
    $('#right').addClass('open');
    $('#left').removeClass('active');

    $('#left').off('mouseenter mouseleave').hover(function(){
        if($('#right').hasClass('active')){
            $('#right').toggleClass('open');
        }
    });
});

DEMO - Using a separate indicator for an active menu


Post a Comment for "Jquery Toggleclass Conflict"