Search code examples
jqueryclickout

Clickout in jquery


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


Solution

  • 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.