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>
<div class="result">
Result 2
</div>
...
</div>
</div>
var searchBar = {
init : function(){
$('input[name=search]').focus(searchBar.openSearch);
$('input[name=search]').blur(searchBar.closeSearch);
$('div.result').each(function(e){
$(this).click(draftboardDynamic.selectResult);
});
},
openSearch : function(e){
$('div.results').show();
},
closeSearch : function(e){
$('div.results').hide();
},
selectResult : function(e){
console.log($(this));
},
}
$(document).ready(searchBar.init);
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:
.blur
event when hovering over div.result
. Rebind it on mouseout..blur
, bind a click event to the document and check that the target is not one of the search components.