MojoDK MojoDK - 7 months ago 25
Javascript Question

Delay on jquery keyup?

I'm trying to create my own "autocomplete", but when I type a letter (eg. w for word), then there's a splitsecond delay - enough to annoy the eye.

Here's my testcode:

CSS:

#txtSearchAutocomplete {
background-color: white !important;
position: absolute;
top: 0;
width: 100%;
font-size: 20px !important;
border: none !important;
color: gray;
}

#txtSearch {
background-color: transparent !important;
position: absolute;
top: 0;
width: 100%;
font-size: 20px !important;
border: none !important;
}


HTML:

<span style="position: relative; display: inline-block; width:100%; top: -18px;">
<input type="text" id="txtSearchAutocomplete" disabled >
<input type="text" id="txtSearch">
</span>


JS:

$(document).ready(function($) {
$("#txtSearch").focus();

$("#txtSearch").keyup(function(e) {
var autocomplete = ['word', 'excel'];
var $txtAutocomplete = $("#txtSearchAutocomplete");
var txt = $("#txtSearch").val().trim().toLowerCase();

$txtAutocomplete.val("");

if (txt == "") return;

for (i = 0; i < autocomplete.length; i++) {
var entry = autocomplete[i];
if (entry.indexOf(txt) == 0) {
$txtAutocomplete.val(entry);
break;
};
};
});
});


And a fiddle sample:
https://jsfiddle.net/25gwz1qu/1/

If you type in the letter w - delete it - type it again and so on, then you will notice a small delay. It might seam that the delay is a bit longer in IE.

Any idea how to get rid of this delay?

Thanks

Answer

The reason for the delay you are seeing is because the event triggers once the user lets go of the key. In that case, the oninput is the way to go. The event triggers when the textbox input changes.

$("#txtSearch").on('input', function(e) { ... })