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; }
So, for detecting a click outside an element, it would be best if you add a listener to the whole document element. Consequently, the main loop will go up the DOM from the clicked target element to search if the ancestor of that element belongs to the flyout container.
Answer: Use the event. target Property target property to detect a click outside of an element such as dropdown menu. This property returns the DOM element that initiated the event.
To hide an element when clicked outside: Add a click event listener to the document object. On each click, check if the clicked element is outside of the specific element using the contains() method. If the clicked element is outside, hide the original element.
We can use CSS absolute positioning to overlap elements, but there's some advantages to using CSS grid instead. Let's explore using CSS grid as an alternative to position absolute.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With