Thomas Thomas - 1 year ago 75
Javascript Question

Detect click inside/outside of element with single event handler

Suppose I have one div in my page. how to detect the user click on div content or outside of div content through JavaScript or JQuery. please help with small code snippet.

Edit: As commented in one of the answers below, I only want to attach an event handler to my body, and also want to know which element was clicked upon.

Answer Source

In JavaScript (via jQuery):

$(function() {
    $("body").click(function(e) {
        if ( == "myDiv" || $("#myDiv").size()) { 
            alert("Inside div");
        } else { 
           alert("Outside div");


<div id="myDiv"></div>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download