Saturday 28 November 2009

How to detect clicked on outside of a particular div?

This is the part of my work on java script. I need to detect in my code, whether I clicked on a particular div or out of a div. So, what is the best way? Get he user clicked position and compare them with div coordinates? No that's not a good solution. Then how we need to do? Below is the best way of implementing it.

document.onclick = clickEvent;
function clickEvent(e) {
var targ;
if (!e) var e = window.event;

if (e.target) targ = e.target;
else if (e.srcElement) targ = e.srcElement;

//if (targ.nodeType == 3) // defeat Safari bug

if (targ.nodeName != "HTML") {
while (targ.nodeName != "BODY") {
if (targ.id && targ.id == 'divGrid') {
return false;
} else {
targ = targ.parentNode;
}
}
} //This is the place where you need to write code when you click outside of the div.
}

Hope this helps in solving some problems. Look for more.

No comments:

Post a Comment