skip to Main Content

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


  1. 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:

    $("ul").not('.mobile-menu').click(...)
    

    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 the div in another manner as well, such as adding a .menu class.

    <div class="menu">...</div>
    <div class="menu mobile-menu">...</div>
    

    In this case you could select the non-.mobile-menu one with:

    $('.menu').not('.mobile-menu').click(...)
    

    Not adding the .menu class and using $('.div').not('.mobile-menu') would select every single div on the page that does not have .mobile-menu, not just the one you’re interested in.

    Login or Signup to reply.
  2. Or even better, use the :not pseudo selector, in your case:

    $('html:not(.mobile-menu)')...
    

    or

    $('body:not(.mobile-menu)')...
    

    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:

    $('body').click(function(){
        if ($(this).closest('.mobile-menu').length === 0) {
            //do stuff here
        }
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search