Hiding the suggestion list of an autocomplete AJAX control on blur
I am implementing an AJAX "autosuggest" box: the user types a string in an input text field, a hidden div with a table is shown, and then he/she can click on a row or scroll the list with the up/down arrows; in the meantime, the focus is still kept on the input text field.
Everything works mostly fine, but there is a detail which I am not able to implement, which seems conceptually difficult or even impossible. I would like to hide the suggestion list when the user moves the cursor to another input field, or just clicks on an empty point of the window. This is not difficult to achieve by itself, I just added a calback OnBlur; but this breaks the selection of the item OnClick, since the onblur event is triggered before the click, and then the DIV disappears before the onclick开发者_Go百科 event gets triggered...
I thought about implementing an onclick callback on the whole window, and then check where the click occurred, but this seems a bit too awkward and contorted. Does anybody have a better idea? Thanks!
I was working on the same issue and came up with following solution. Autosuggest list made hidden onclick of document which also works in IE(window.onclick does not works in IE).
document.onclick = function(ev)
{
this.hideAutosuggestListDiv();
};
this.hideAutosuggestListDiv = function()
{
this.div.style.display = 'none';
};
I had a simular problem but came up with a bit of a different solution:
document.onclick = closeSuggest;
function closeSuggest() {
document.getElementById('suggestions').style.display = "none";
}
function catchTAB(event) {
if(event.keyCode ==9) {
closeSuggest();
document.getElementById('ELEMENT').focus(); //the element that is currently focused
}
}
Hope this helps
For those working with jquery the focusout
event trigger works perfectly for this:
$('#input-box').focusout(function() {
$('#suggestions').fadeOut();
});
I am currently trying to solve the same problem.
Partial solution:
Use a function to wait a fraction of a second before you clear the autosuggest DIV
function pause(milliseconds) {
var dt = new Date();
while ((new Date()) - dt <= milliseconds) { }
}
onBlur="pause(500);clearAutosuggestBox()"
However, this solution is not elegant and it doesn't work in all browsers.
In looking at some of the popular autosuggest boxes, I have not come across one that makes the autosuggest info go away when you click outside, rather they usually time out and disappear.
Best of luck.
精彩评论