tags:

views:

121

answers:

3

Hello,

Could somebody help me with this? :

I have a button that when clicked it shows a certain div. This div has several descendants. Now, what I want is that when I click somewhere else in the document, but not in any of those descendants that this div disappears. what I thought was to use the not selector like this:

$("#button").click(function(){
    $("#mydiv").show();
    $(document.body).not($("#mydiv").children()).one('click',function(e) {
        $("#mydiv").hide(); 
    });
        return false;   
});

but this is not working! Any idea why? thanks

A: 

Use closest to check if the target is a descendant of mydiv.

$("#button").click(function(){
    $("#mydiv").show();
    $(document.body).click(function() {
        if ($(event.target).closest("#mydiv").length == 0)
            $("#mydiv").hide();     
    });
    return false;   
});

You can't use one() because the event would get removed if you click inside mydiv. You'll have to do some custom event unbinding if you want to remove it.

Joel Potter
that does not work because the $(this) object is the document.body
Manuel
Sorry. Forgot you had to use target. Fixed.
Joel Potter
A: 

The problem might be with what you are passing in to the .not() to exclude

.not($("#mydiv").children())

At the moment you are passing a jQuery object in, but from the docs, what is passed into .not() should be either a string selector, a DOM element or an array of DOM elements. Therefore simply converting the jQuery object to an array of elements should work

$("#button").click(function(){
    var myDiv = $("#mydiv").show();
    $(document.body).not(myDiv.children().get()).one('click',function(e) {
        myDiv.hide();     
    });
        return false;   
});
Russ Cam
well, I have learned something new now, but still doesnt solve my problem. Thanks anyway
Manuel
+1  A: 

How about checking the click event to see what was clicked? Specifically look at the event.target.

$(document).click(function(event) {
  var target = $(event.target);

  if (!target.attr('id').match(/^mydiv/) && target.parents('#mydiv').length == 0) {
    $('#mydiv').hide();
  }
});

I have used this code before to close an open window when someone clicks anywhere but the window.

Topher Fangio
I don't wanna exclude only that id but also all the descendants of that element
Manuel
Try the updated code, it should check that the target doesn't have any parents whose id is "mydiv".
Topher Fangio
perfect! Thanks
Manuel