2

I have a search box with search suggestion:

<input id="searchBar" />
<div id="searchSuggestion"></div>

The div searchSuggestion is automatically updated via jQuery ajax when an input is made (code not shown). To hide / show the autocomplete suggestions (which appear below the search textbox), I use:

$searchBar.blur(function () {
    $searchSuggestion.css("display", "none");
});
$searchBar.focus(function () {
    $searchSuggestion.css("display", "");
});

So far so good.

Now, I want to auto-fill the textbox when a user clicks on a search suggestion item:

$searchSuggestion.on("click", ".item", function () {
    alert("clicked");
});

The problem is, clicking the search suggestion item causes the textbox to lose focus, therefore display:none is set on the search suggestion items, which causes the click event to not fire!

If I remove the display:none code, everything works fine.

How can I work around this conflict?

kevin
  • 2,196
  • 1
  • 20
  • 24

2 Answers2

2

Ended up with this solution, which prevents the mousedown event from propagating and causing the element to lose focus before click (which requires mouseup) is fired:

$searchSuggestion.on("mousedown", function (e) {
    e.preventDefault();
}).on("click", ".item", function () {
    alert("clicked");
});
Community
  • 1
  • 1
kevin
  • 2,196
  • 1
  • 20
  • 24
1

You can workaround this by adding a small timeout in your blur handler, try this for example:

$searchBar.blur(function () {
    setTimeout(function() {
        $searchSuggestion.css("display", "none");
    }, 150);
});