I implemented a search box that acts like a filter. When the user clicks a button in the search area, a drop-down list is displayed showing all the possible options. Input in the search box filters the results. A click outside the window hides the results.
It uses the following HTML / CSS hearchy
<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>
I use jQuery to show / hide the focus / blur dropdown event list
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 works very well and I can open, close and search (JS removed for clarity) without any problems. The only bit I came across is the selection of results. The blur event seems to trigger the result.click events, and the handler is never called. I can fix this problem by removing the blur snap, however I cannot figure out how to close the drop-down list when the input loses focus.
Any ideas?
source share