Thomas Thomas - 8 months ago 51
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>