Alex Rivera | Logout

Action on blur except when specific element clicked with jQuery

Asked 2011-02-04T19:02:44.010
35

There are two elements in play:

$('#myInput') // an input field for search
$('#myList') // a list to display search results

I want to hide the list when the input no longer has focus, like so:

$('#myInput').blur(function() {
  $('#myList').hide();
});

This works great, except when a list item is clicked, because the blur event fires and hides the list before the click is registered. The goal is for the list to stay visible when any part of the list is clicked, even though this will cause the input to blur.

How can I do this? Thanks!

Edit
Report

1 Answer

1

The best way to do this is to attach an event handler to the body element, then another handler to the list that stops event propagation:

$(body).click(function () {
    $("#myList").hide();
});

$("#myList").click(function (e) {
    e.stopImmediatePropagation();
});

This listens for a click outside of #myInput and hides #myList. At the same time, the second function listens for a click on #myList and if it occurs, it prevents the hide() from firing.

answered 2011-04-06T02:56:52.107

Your Answer