jay stephens jay stephens - 3 months ago 8
CSS Question

addClass is removed from button when clicking inside Dropdown menu

The button that activates the dropdown uses click rather than hover, on click, I've used jquery to add class, and to remove the class when clicked outside the button I used $(document).click. The problem is, when I click inside the dropdown menu, the class gets removed (Which will obviously happen)

Is there anyway to make an exception for the dropdown div or is there any fix I can use to solve the issue.

$(document).ready(function(){

$(".menu1TextContainer").click(function(event){

$(".menu1Container").toggleClass("addclass")
event.preventDefault();

});

$(document).click(function(event) {
if(!$(event.target).is(".menu1TextContainer")){
$(".menu1Container").removeClass("addclass"); //make all inactive
}
});

});


https://jsfiddle.net/9j3k61rg/3/

Thanks!

Answer

You just simply need to skip class adding/removing when your dropdown is open. I have made a working code for you:

I updated your snippet, see here: https://jsfiddle.net/9j3k61rg/4/

$(document).click(function(event) {
if (!$(event.target).is(".menu1TextContainer") && !$(event.target).is("#menu1Dropdown")) {
         $(".menu1Container").removeClass("addclass"); //make all inactive
     }
        });

});