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,139
  • 1
  • 21
  • 23

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,139
  • 1
  • 21
  • 23
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);
});
Tha'er M. Al-Ajlouni
  • 10,992
  • 7
  • 35
  • 37
  • isnt' this missing the whole.... clearTimeout when clicking on a suggestion item portion? – Kevin B Jan 17 '17 at 16:22
  • Is it possible to do this without timeout? Ideally, the moment when the user clicks the suggestion, the focus is already known. I just need the click() event to fire before the blur() event. – kevin Jan 17 '17 at 16:22
  • @KevinB No need to clear `timeout`s since it creates only one instance, intervals on the other hand needs to be cleared – Tha'er M. Al-Ajlouni Jan 17 '17 at 16:23
  • @Tha'erAl-Ajlouni Right, but... if you don't clear it, then it's going to hide shortly after clicking a suggestion item... I guess that works if it's what you want – Kevin B Jan 17 '17 at 16:24
  • @kevin the `blur` handler is not aware of `click` event, and cannot know which item was clicked! – Tha'er M. Al-Ajlouni Jan 17 '17 at 16:24
  • @KevinB yes that was the intention, click then hide as required in the question. – Tha'er M. Al-Ajlouni Jan 17 '17 at 16:25