How do I hide an element on a click event anywhere outside of the element? How do I hide an element on a click event anywhere outside of the element? jquery jquery

How do I hide an element on a click event anywhere outside of the element?


If I understand, you want to hide a div when you click anywhere but the div, and if you do click while over the div, then it should NOT close. You can do that with this code:

$(document).click(function() {    alert("me");});$(".myDiv").click(function(e) {    e.stopPropagation(); // This is the preferred method.    return false;        // This should not be used unless you do not want                         // any click events registering inside the div});

This binds the click to the entire page, but if you click on the div in question, it will cancel the click event.


Try this

 $('.myDiv').click(function(e) { //button click class name is myDiv  e.stopPropagation(); }) $(function(){  $(document).click(function(){    $('.myDiv').hide(); //hide the button  });});

I use class name instead of ID, because in asp.net you have to worry about the extra stuff .net attaches to the id

EDIT-Since you added a another piece, it would work like this:

 $('.myDiv').click(function() { //button click class name is myDiv  e.stopPropagation(); }) $(function(){  $('.openDiv').click(function() {  $('.myDiv').show();   });  $(document).click(function(){    $('.myDiv').hide(); //hide the button  });});


As of jQuery 1.7 there's a new way to handle events. I thought I'd answer here just to demonstrate how I might go about doing this the "new" way. If you haven't, I recommend you read the jQuery docs for the "on" method.

var handler = function(event){  // if the target is a descendent of container do nothing  if($(event.target).is(".container, .container *")) return;  // remove event handler from document  $(document).off("click", handler);  // dostuff}$(document).on("click", handler);

Here we're abusing jQuery's selectors and bubbling of events. Note that I make sure I clean the event handler up afterwards. You can automate this behaviour with $('.container').one (see: docs) but because we need to do conditionals within the handler that isn't applicable here.