Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clickout in jquery

Tags:

jquery

click

out

What is the easiest way to do a clickout in jquery Where a div box hides if clicked anywhere outside it.

like image 214
Hussein Avatar asked Jan 28 '11 20:01

Hussein


People also ask

How to handle outside click in jQuery?

To detect a click outside of an element, attach the click event handler to the area outside of the element such as the document. In the event handler check the target for the element or an element descendant by using the jQuery closest method.

How to 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.


1 Answers

I don't like the solutions that use stopPropagation because often I am using event bubbling to manage various links. I don't want to have to worry that they might stop working if the box exists. My choice would look something like this:

var $box = $('#box');
$(document.body).click(function(){
    if (!$box.has(this).length) { // if the click was not within $box
        $box.hide();
    }
});

The has function filters the selection and returns elements only if they contain the element passed as the parameter (you can also use a selector string, but that isn't relevant here). If the click was outside the box, length will be 0 so the conditional will pass and the box will be hidden.

This should be optimised by setting a boolean value for whether the box is currently visible and only doing the has call if it is currently visible.

like image 179
lonesomeday Avatar answered Oct 05 '22 04:10

lonesomeday