Frage

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; }
War es hilfreich?

Lösung

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/

Andere Tipps

You can use jQuery's $.on() / $.bind() (depending on your jQuery version) to listen for the mousedown event on the outer div while preventing the inner div from reacting to the mousedown event using event.stopPropagation() like so:

$('.inner').on('mousedown', function(e){
    e.stopPropagation()
});
$('.outer').on('mousedown', function(){
    alert('outer');
    return false;
});

Update Fiddle Here

I hope this helps!

$(document).mousedown(function (e) {
    var div = $(".inner");
    if (!$(e.target).is('.inner') && div.has(e.target).length === 0) {
        console.log('clicked outside of .inner');
    }
});
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top