Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mouse click somewhere else on page (not on a specific div)

I want to close a little pop-up box in page when user has clicked anywhere on the page other than box area. how to find it?

like image 731
coure2011 Avatar asked Aug 09 '10 12:08

coure2011


People also ask

How do you find a click outside of an element?

Answer: Use the event. target Property You can use the event. target property to detect a click outside of an element such as dropdown menu. This property returns the DOM element that initiated the event.

Can you give a Div an onClick?

To set an onClick listener on a div element in React:Set the onClick prop on the div. The function you pass to the prop will get called every time the div is clicked.


2 Answers

$(document.body).click(function(e){
   var $box = $('#little-pop-up-box-id');
   if(e.target.id !== 'little-pop-up-box-id' && !$.contains($box[0], e.target))
      $box.remove();
});

e.target is the DOM node which received the click event. I'm checking first if the ID of that element is not the one we are looking for.

The second check !$.contains($box[0], e.target) makes sure, that the DOM node of invocation is not within the element we want to hide.

Well, I guess it's plugin time! :

(function($){
   $.fn.outside = function(ename, cb){
      return this.each(function(){
         var $this = $(this),
              self = this;
         $(document.body).bind(ename, function tempo(e){
             if(e.target !== self && !$.contains(self, e.target)){
                cb.apply(self, [e]);
                if(!self.parentNode) $(document.body).unbind(ename, tempo);
             }
         });
      });
   };
}(jQuery));

synopsis

$('#container').outside('click', function(e){
    $(this).remove();
});

Example:

http://www.jsfiddle.net/qbDKN/30/

like image 160
jAndy Avatar answered Sep 20 '22 18:09

jAndy


@jAndy's solution is good, but I wanted to mention Ben Alman's "Outside Events" plugin as well. Here's a quick example using it:

$("#popup").bind("clickoutside", function(event){
  $(this).hide();
});
like image 25
jmar777 Avatar answered Sep 17 '22 18:09

jmar777