user2057190
user2057190

Reputation:

how detect mouse click area in document - jquery - javascript

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

Upvotes: 1

Views: 6860

Answers (3)

Jasmeen
Jasmeen

Reputation: 906

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

};

Upvotes: 0

VisioN
VisioN

Reputation: 145408

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/

Upvotes: 3

Tomáš Zato
Tomáš Zato

Reputation: 53149

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
   }

Upvotes: 3

Related Questions