Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery document body one click event

Tags:

jquery

events

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

like image 858
Manuel Avatar asked Nov 30 '22 11:11

Manuel


1 Answers

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.

like image 100
Topher Fangio Avatar answered Dec 04 '22 23:12

Topher Fangio