Wednesday, April 6, 2011

Detect if Clicked Inside of a Div Container


// Following code will enable you to detect if a click occurred inside of a particular div through JavaScript.
// An example scenario would be a calander control being displayed as a popup. we need to close the
// calendar when the user clicks outside of the calendar area. If the user clicks somewhere inside the calender
// area the calendar would remain without being closed.

function EscapeClick(e)
{
var divContainer = document.getElementById('id_of_the_containerdiv');
var target = (e && e.target) || (event && event.srcElement);

if( checkParent(target,divContainer)!= true)
{
return false;
}
else
{
//Perform the hiding function , if its a calendar control.
// OR whatever you wish.
}
}

function checkParent(t,parentContainer){
while(t.parentNode)
{
if(t==parentContainer)
{
return false;
}
t=t.parentNode
}
return true
}
document.body.onclick = EscapeClick;