I'm trying to modify jQuery's autocomplete widget to have the input's background color change while the script is searching for suggestions. Here is my attempt (or have a look at my attempt on jsfiddle):
html
<label for="numbers">Numbers: </label>
<input id="numbers" />
javascript
var numbers = [],
nb = 10000,
i;
for (i = 0; i < nb; i += 1) {
numbers.push(i.toString());
}
function color (color) {
$('#numbers').css({
background: color
});
}
$("#numbers").autocomplete({
source: numbers,
search: function (event, ui) {
console.log('search event fired');
color("red");
},
open: function (event, ui) {
console.log('open event fired');
color("green");
},
close: function (event, ui) {
console.log('close event fired');
color("white");
}
});
As you can see, I'm logging the search
, open
and close
events so I can see when they are fired.
As expected, typing in 5
(an existing value) fires the search
event and logs the corresponding message, and, a few seconds later, fires the open
event and logs its corresponding message. Since I put 10000 entries in there, there is a noticeable delay between the search
event and the open
event (something like 1 second).
What baffles me is that when the log message associated to the search
event appears, it is not followed by the background color changing to red as should be expected. Instead, it remains white until the open
event occurs, then becomes green (as expected after the open event). If, however, I type in a
(a non-existing value), the background color goes red without problem (notice the open event never occurs in this case because no corresponding value is found). What's happening here?
For the curious, I'm ultimately trying to have a little loading
icon appear while the search is underway (a feature which I am surprised isn't shipped with the widget out of the box). The background color change is a first step in that direction.
UPDATE
I made another attempt which shows that the instruction following console.log
is indeed called, but the visual effects appear only much later. Here is the code I'm using:
$("#numbers").autocomplete({
source: numbers,
search: function (event, ui) {
console.log('search event fired');
$('#numbers').css({
marginTop: "5em"
});
console.log('search callback done');
}
});
If you try it out, you'll see that both messages are logged before the field is displaced by the addition of a top margin. Somehow, the margin is added at the right time, but the page is not being redrawn at the right time...