Thomas Thomas - 22 days ago 5
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.
thanks.

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

In JavaScript (via jQuery):

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

In HTML:

<div id="myDiv"></div>