Jason George Jason George - 1 year ago 122
HTML Question

Blur issues on drop-down search box in jQuery

I've implemented a search box that acts as a filter. When a user clicks in the search area, a drop-down box is displayed showing all of the possible options. Typing in the search box filters the results. Clicking outside of the box hides the results.

It uses the following HTML/CSS heiarchy

<div class="search">
<input type="text" name="search" value="search" placeholder="search"/>
<div class="results">
<div class="result">
Result 1
<div class="result">
Result 2

I use jQuery to show/hide the dropdown on focus/blur events

var searchBar = {
init : function(){
openSearch : function(e){
closeSearch : function(e){
selectResult : function(e){

This works quite well and I can open, close, and search (JS removed for clarity) without issue. The only bit I'm having trouble with is selecting results. The blur event seems to trigger before result.click events and the handler is never called. I can correct this issue by removing the blur binding, however, I can't figure out how to close my drop-down box when the input loses focus.

Any ideas?

Answer Source

This is a tough one because the .blur event will always fire before the .click. There are two possible solutions, neither of which is particularly desirable:

  1. Unbind the .blur event when hovering over div.result. Rebind it on mouseout.
  2. Instead of doing this with .blur, bind a click event to the document and check that the target is not one of the search components.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download