Thursday, June 10, 2010

How to detect a click outside an element to close overlay or modal box ?

function clickedOutsideElement(elemId) {
    var theElem = getEventTarget(window.event);
    while(theElem != null) {
        if(theElem.id == elemId)
            return false;
        theElem = theElem.offsetParent;
    }
    return true;
}


function getEventTarget(evt) {
    var targ = (evt.target) ? evt.target : evt.srcElement;
    if(targ != null) {
        if(targ.nodeType == 3)
            targ = targ.parentNode;
    }
    return targ;
}


document.onclick = function() {
    if(clickedOutsideElement('divTest'))
        alert('Outside the element!');
    else
        alert('Inside the element!');
}

2 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Firefox doesn't get it. :(
    Chrome 16: OK
    IE9: OK

    ReplyDelete