Search code examples
jquerymouseeventmousedown

Capturing click outside of a absolute positioned div


http://jsfiddle.net/dgjJe/1/

In the above jsfiddle I am trying to capture when the user clicks outside of the .inner div but I can't seem to get it working.

HTML:

<div class="outer">
    <div class="inner"></div>
</div>

Javascript:

$(document).mousedown(function (e) {
    var div = $(".inner");
    if (div.has(e.target).length === 0) {
        alert('clicked outside of .inner');
    }
});

CSS:

.outer { width:200px; height:200px; border:1px solid #000; position:relative; }
.inner { width:100px; height:100px; border:1px solid #000; position:absolute; top:25px; left:25px; }

Solution

  • div variable in your code refers to the .inner element, so it doesn't have .inner child element. Based on the structure of markup, has method is not useful here. You can use is method:

    $(document).mousedown(function(e) {
        if ( !$(e.target).is('.inner') ) {
            alert('clicked outside of .inner');
        }
    });
    

    http://jsfiddle.net/MJmPF/

    The above method doesn't work if the .inner has children elements, for this case you can use closest method:

    $(document).mousedown(function(e) {
        if ( !$(e.target).closest('.inner').length ) {
            alert('clicked outside of .inner');
        }
    });
    

    http://jsfiddle.net/wHpa8/