Detect click outside element

by supriya parab

HTML

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


















<!-- Post Info -->
<div style='position:fixed;bottom:0;left:0;    
            background:lightgray;width:100%;'>
    Based off this SO Question: <a href='http://stackoverflow.com/q/6635659/1366033'>jQuery bind click *ANYTHING* but *ELEMENT*</a><br/>                
    Based off this SO Question: <a href='http://stackoverflow.com/q/152975/1366033'>How to detect a click outside an element?</a><br/>    
<div>

CSS

#myDiv {
    width: 100px;
    height: 100px;
    background: seagreen;
}

JavaScript

$.fn.clickOff = function(callback, selfDestroy) {
    var clicked = false;
    var parent = this;
    var destroy = selfDestroy || true;
    
    parent.click(function() {
        clicked = true;
    });
    
    $(document).click(function(event) { 
        if (!clicked) {
            callback(parent, event);
        }
        if (destroy) {
            //parent.clickOff = function() {};
            //parent.off("click");
            //$(document).off("click");
            //parent.off("clickOff");
        };
        clicked = false;
    });
};

$("#myDiv").click(function() {
    alert('clickOn');
});

$("#myDiv").clickOff(function() {
    alert('clickOff');
});