Jquery document object one click event

Can someone help me with this?

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

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

but it does not work! Any idea why? thanks

+4
source share
3 answers

How about checking the click event to see what was clicked? In particular, see event.target .

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

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

+15
source

Use the closest one to check if the target is a mydiv stream.

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

You cannot use one() because the event will be deleted if you click inside mydiv . You will need to disable a single event if you want to delete it.

+5
source

The problem may be that you are passing .not() to throw an exception

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

At the moment you are passing a jQuery object, but from the documents , what is passed to .not() should be either a string selector, a DOM element or an array of DOM elements. Therefore, simply converting a 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; }); 
0
source

All Articles