Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML Select: Eliminating browser Delay on keypress-to-change?

Consider the following HTML:

<select>
    <option>Aardvark</option>
    <option>Buffalo</option>
    <option>Camel</option>
    <option>X-ray Fish</option>
    <option>Yak</option>
    <option>Zebra</option>
</select>

In most browsers, when the select element has focus, pressing a key will change the selected value to the next option that begins with the character typed. For instance, pressing 'B' on the keyboard while the <select> element above has focus changes the selected value to "Buffalo". Pressing 'Z' after that will change the value to "Zebra".

But I just discovered that, at least in Firefox 6 and Safari 5 on my PC, there is a delay before I can press-to-select the next value. In the specific example above, if I press "B" and then press "Z" less than a second later, nothing appears to happen.

However, in further testing (with jQuery) I discovered that the Javascript events 'keydown', 'keyup', and 'keypress' ARE all fired as you'd expect, no matter how rapidly you press the keys. The browsers themselves just don't switch the selected option until a certain period of time has passed.

Is there any way to get around this?

like image 365
Brian Lacy Avatar asked Sep 05 '25 20:09

Brian Lacy


2 Answers

It seems to be possible with cloning. It's a really dirty hack but works just fine in Chrome: http://jsfiddle.net/pimvdb/v6qy8/2/.

$('select').keyup(function() {
    var newSelect = $(this).clone(true).val($(this).val());
    $(this).replaceWith(newSelect);
    newSelect.focus();
});
like image 80
pimvdb Avatar answered Sep 08 '25 11:09

pimvdb


I did it by interrupting the keyevent and placing a preventDefault() at the top of the function. I use the Enter key to break the delay and submit what I've typed already.

if (eventinfo.keyCode == 13) {
    eventinfo.preventDefault();
    var search = document.getElementById("searchtag");
    var value = search.value;
    mainPage.searchAdd(value).done(
        function () {
           search.value = "";
           search.focus();
        }
    );
}
like image 44
BrianDwayne Avatar answered Sep 08 '25 10:09

BrianDwayne