1

I have a page with a div element in it. i want when i clicked on outer area of that div element, then fade it out.

but i don't know how detect area of mouse click. how detect that mouse click point is out of div area or not??

  • 2
    possible duplicate of [Use jQuery to hide a DIV when the user clicks outside of it](http://stackoverflow.com/questions/1403615/use-jquery-to-hide-a-div-when-the-user-clicks-outside-of-it). See also http://stackoverflow.com/search?q=jquery+click+outside+div – JJJ Feb 09 '13 at 14:12

3 Answers3

3

One possible jQuery solution:

$(document).on("click", function(e) {
    var $div = $("#divId");
    if (!$div.is(e.target) && !$div.has(e.target).length) {
        $div.fadeOut();
    }
});

DEMO: http://jsfiddle.net/5Jb5b/

VisioN
  • 143,310
  • 32
  • 282
  • 281
  • Not IE compatible. I don't demand you to write function with all compatibility handling, but you should point out which things must be taken care of. – Tomáš Zato Feb 09 '13 at 14:26
  • 2
    @TomášZato Eh? It's jQuery. It **is** compatible with IE. If you think that `e.target` in `on` method is derived in the same way as in `addEventListener`, you are wrong. – VisioN Feb 09 '13 at 14:27
  • @Stano Updated in some sense :) – VisioN Feb 09 '13 at 15:05
3

This is not very complicated - you have two options:
1. Asign onclick event to the outer area.

<div id="outer" onclick="$("#inner").fadeOut();">
    <div id="inner" onclick="event.cancelBubble=true;/*disable bubling*/">Inner Div</div>
</div>

2. Traverse the dom and compare event.target (event.srcElement)

   document.addEventListener("click", function(event) {
       var body = document.body;
       var target = event.target!=null?event.target:event.srcElement;
       var inner = document.getElementById("inner");
       while(target!=body) {
         if(target==inner)    //This means our inner element is clicked - or one of its children
           return false;
         target=target.parentNode;   //Go UP in the document tree
       }
       $("#inner").fadeOut();   //If we got here, none of element matched our inner DIV, so fade it out
   }
Tomáš Zato
  • 50,171
  • 52
  • 268
  • 778
0

function clickOn(e) {

var target = e.target;
var optn = [];
optn.id = target.id; 
optn.optnClass = target.className.split(' ');
optn.optnType = target.optnName.toLowerCase();
optn.parent = target.parentNode; 
return optn;

}

document.body.onclick = function(e) {

elem = clickOn(e);
var option_id = elem.id;
alert( 'option ID: '+option_id); // From id or other properties you can compare and find in which area mouse click occured

};

Jasmeen
  • 876
  • 9
  • 16