Dibish Dibish - 3 months ago 19
HTML Question

Javascript Detect Click event outside of div

I have a div with id content-area, when some one click outside of that div, i would like to alert user that you clicked outside of content area. I don't know how can i do it in JavaScript. Please help me to solve this issue. You help is much appreciated. Thanks in advance.

<div id = "outer-container">

<div id = "content-area">

Display Conents

</div>
</div>

Answer

In pure Javascript

Check out this fiddle and see if that's what you're after!

document.getElementById('outer-container').onclick = function(e) {
    if(e.target != document.getElementById('content-area')) {
        document.getElementById('content-area').innerHTML = 'You clicked outside.';          
    } else {
        document.getElementById('content-area').innerHTML = 'Display Contents';   
    }
}

http://jsfiddle.net/DUhP6/2/