Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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; }
like image 829
Amir Avatar asked May 23 '13 19:05

Amir


People also ask

How do I detect a click outside an element?

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.

How do you trigger a click outside?

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.

How do I hide a div when clicking outside?

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.

What can I use instead of position absolute?

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.


1 Answers

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/

like image 103
undefined Avatar answered Sep 18 '22 20:09

undefined