Skip to content Skip to sidebar Skip to footer

Close A Menu With An Anywhere Click

As you guys can see, I have a drop down menu. I have a lot of columns, each one has an option to open the menu. $('.optionCont').live('click', function(){ $('.dropMenuCont').sl

Solution 1:

Register a one-off handler inside the callback to make sure the next click closes the menu:

$(".optionCont").live("click", function(ev){
    $(".dropMenuCont").slideUp();
    if($(this).next().css("display") == "none"){
        $(this).next().slideDown();
    }else{
        $(this).next().slideUp();
    }
    ev.stopPropagation();

    $(document).one('click', function() {
             $(".dropMenuCont").slideUp();

    });
});

See http://jsfiddle.net/alnitak/GcxMs/

Solution 2:

$(".optionCont").click(function(e){
    $(".dropMenuCont").slideUp();
    if($(this).next().css("display") == "none"){
        $(this).next().slideDown();
    }else{
        $(this).next().slideUp();
    }
    e.preventDefault();
    e.stopPropagation();
    returnfalse;
});

$(document).click(function() {
     $(".dropMenuCont").slideUp();
});

Here is the JSFiddle

Solution 3:

Try something like:

$(document).click(function(e) {
   if ($(e.target) != myEl)
       myEl.slideUp();
})

Alternative: working example.

Source:

$(".optionCont").live("click", function(e) {
    var that = this;
    $(document).click(function(e) {
        console.log(e.target);
        console.log(that);
        if (e.target != that) {
            e.stopPropagation();
            e.preventDefault();
            $(".dropMenuCont").slideUp();
        }
    });
    if ($(this).next().css("display") === "none") {
        $(this).next().slideDown();
    } else {
        $(this).next().slideUp();
    }
    e.stopPropagation();
    e.preventDefault();
});

Solution 4:

Just bind the click to <body>

$('body').click(function() {
  $(".dropMenuCont").slideUp();
});

$('.dropMenuCont').click(function(e){
  e.stopPropagation();
});

Solution 5:

$('body').bind("click",function (){
    $(".dropMenuCont").slideUp();
});
$('.dropMenuCont').click(function(event){
    event.stopPropagation();
});

I think a better idea to check if something is hidden is to toggle the class on your menu in a callback of the animation and then check it with hasClass.

Post a Comment for "Close A Menu With An Anywhere Click"