how detect mouse click area in document - jquery - javascript - Stack Overflow

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

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??

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??

Share Improve this question edited Nov 29, 2013 at 3:19 asked Feb 9, 2013 at 14:10 user2057190user2057190 1
  • 2 possible duplicate of Use jQuery to hide a DIV when the user clicks outside of it. See also stackoverflow./search?q=jquery+click+outside+div – JJJ Commented Feb 9, 2013 at 14:12
Add a ment  | 

3 Answers 3

Reset to default 3

This is not very plicated - 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 pare 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
   }

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/5Jb5b/

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 pare and find in which area mouse click occured

};

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744372017a4571001.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信