roryok
roryok

Reputation: 9645

Detecting a click outside either of two elements?

I've got a little autocomplete dropdown which I want to hide when someone clicks outside the textbox. I've been using this so far

$("#input-group_ids").on("blur", function () {
    $(".input-dropdown").hide();
});

However my autocomplete dropdown has an overflow and a scroll bar if there are more than 10 options. When using the above code, clicking on the scroll bar closes the dropdown.

I need the dropdown to close only if the click is outside the textbox AND the dropdown itself. How do I do that?

Upvotes: 2

Views: 311

Answers (6)

Benjamin
Benjamin

Reputation: 2670

Not yet tested hope this will work

$("html").click (function () {
    $(".input-dropdown").hide();
});
$("#input-group_ids, .input-dropdown").click (function (e) {
    e.stopPropagation;
}

Upvotes: 4

roryok
roryok

Reputation: 9645

I found another answer to this which is actually the best version I think

$(document).click(function(e) {
    if (!$('#input-group_ids').is(e.target) && !$('.input-dropdown').is(e.target))
        $('.input-dropdown').hide();
});

This is slightly better than Benjamin's answer as it doesn't stop propagation of any clicks on $("#input-group_ids"), which may have unintended consequences. However I'm accepting Ben's answer as it worked and solved my problem, and he deserves the credit. =)

EDIT: Actually my version is pretty similar to @singe31's version, so I upvoted that one too

Upvotes: 0

springbo
springbo

Reputation: 1096

a little hackish but might work.

$(elementContainingTheDropDownContent).on('mouseleave', function(e){
    $(window).on('click', function(e){
        //close dropdown
    })
}).on('mouseenter', function(){
    $(window).off('click');
})

Upvotes: 0

peter_the_oak
peter_the_oak

Reputation: 3710

In case you won't get clear with the blur event, try to register the click event to an element that is surrounding both the textbox and the dropdown. It may even be the body.

Then in the click event check the event.target element. If it is neither the textbox nor the dropdown, close it.

It feels clumsy, I know, but it is one of several working options.

Upvotes: 1

ShufflerShark
ShufflerShark

Reputation: 387

Have you tried the not selector the name explains it all and might work if you have a container on the dropdown and textbox

Upvotes: 0

singe3
singe3

Reputation: 2105

Try this :

$("*:not(#input-group_ids)").on("click", function () {
    $(".input-dropdown").hide();
});

Not tested because you didn't gave any jsfiddle

Upvotes: 0

Related Questions