I have a sidebar responsive menu that opens when clicked on a button.
The menu has dropdown sub-menus and uses twitter bootstrap template.
I am trying to hide the menu when clicked anywhere on the screen except the menu-button and the menu itself.
But the exception of clicking on menu does not work. It hides even when clicked over the menu. The problem according to me lies in the .not() selector.
What may be wrong here?
The code is:
CSS
.menu-click
{
padding: 5px;
cursor: pointer;
border: solid 1px #ffcccc;
}
.mobile-menu
{
top: 50px;
display: none;
position: absolute;
z-index: 999;
animation-duration:0.5s;
-o-animation-duration:0.5s;
-webkit-animation-duration:0.5s;
-moz-animation-duration:0.5s;
}
JQuery
$(function(){
$("html").not('.mobile-menu').click(function(){
$(".mobile-menu").removeClass("animated fadeInLeft").addClass("animated fadeOutLeft")
});
$(".menu-click").click(function(event){
event.stopPropagation();
});
});
2
Answers
jQuery.not
filters on the matched elements you’re calling it on. What the code in your question is asking for is all<html>
elements that are not.mobile-menu
elements.You probably want something like this:
After discussion in the comments, if you have a
div
with.mobile-menu
on it and you want to check if.mobile-menu
is not on it, you need to identify thediv
in another manner as well, such as adding a.menu
class.In this case you could select the non-
.mobile-menu
one with:Not adding the
.menu
class and using$('.div').not('.mobile-menu')
would select every singlediv
on the page that does not have.mobile-menu
, not just the one you’re interested in.Or even better, use the :not pseudo selector, in your case:
or
for that matter.
If that doesn’t work, you can always go the long way, and monitor clicks on the whole body, and then check in the handler if the parent is the .mobile-menu class: