I am trying to set up an auto-complete search form with jQuery.
I would like to hide the search results div when the field isn’t focused, however if someone tries to click a link within the results, they are unable to since it instantly becomes hidden, since the search field lost focus.
Here is the code:
HTML:
<form>
<input type='search' id='search' placeholder='search' />
</form>
<div id='search-results' style='display:none'>
<ul>
<li><a href='#'>Example Result</a></li>
</ul>
</div>
JavaScript
$("#search").keyup(function() {
query = $(this).val();
if(query.length > 2) {
$("#search-results").html(get_search_results(query)).show();
} else {
$("#search-results").hide();
}
});
$("#search").focus(function() {
if($(this).val().length > 2) {
$("#search-results").show();
}
});
$("#search").blur(function() {
$("#search-results").hide(); //makes it impossible to click results
});
How can I accomplish hiding the results when not in use, but still have them be clickable?
I would recommend setting a function to check if the mouse is over the search-results div.
Like so.
Then have a function that changes it on rollover
then in your function you check if the variable is true
Hope that helps