Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onClickOut (click after leaving the element) [duplicate]

The problem was that I need a "onClickOut"-Event.

For example: You have a DIV viewing on hovering (onMouseOver) some Button or what ever.

If you click outside the element it needs to hide, but if you say $("body").click it also will be hidden when you click into the element itself. :/

Now I listen the mouseposition and when mouseleave() I set a var on clicking into my element. In the next step I listen a generelly click-event (body) but I ask if the var was set. If not it has to be a click outside my element, so I can hide my element.

I hope you can use it:

$("#schnellsuche_box").mouseleave(function() {
    var inside;
    $("#schnellsuche_box").click(function() {
        inside = true;
    });
    $("body").click(function() {
        if(!inside) {
            $("#schnellsuche_box").hide();
        }
    });
    delete inside;
});
like image 660
Froschkoenig84 Avatar asked Aug 21 '13 10:08

Froschkoenig84


2 Answers

You do that by listening to a click on the document level, and inside the event handler you check if the clicked element was #schnellsuche_box or any element inside #schnellsuche_box by using closest(), like so :

$(document).on('click', function(e) {
    if ( ! $(e.target).closest('#schnellsuche_box').length ) 
         $('#schnellsuche_box').hide();
});

FIDDLE

like image 90
adeneo Avatar answered Nov 11 '22 08:11

adeneo


You need to stop the #schnellsuche_box click event from bubbling up to the body click event (that's default event propagation) by doing return false:

$("#schnellsuche_box").click(function() {
    inside = true;

    return false;
});
like image 44
mattytommo Avatar answered Nov 11 '22 08:11

mattytommo