1 year ago
#196861
Tim
timing issues with keydown, keyup, focus, and blur in browsers
The majority of my time is spent on the database side of things and I haven't been keeping up with HTML and javascript developments, especially when it involves any kind of "fancy" UI coding. In 2022, is there a canonical solution to the following dilemma for both desktop and mobile browsers, or is it a "moving target"?
When you want to present the user with a series of HTML input
elements each of which accepts only a single character, as with an "enter your PIN" prompt, automatically setting focus to the next input
when a single (valid) character has been entered, timing issues can cause havoc, especially when the user has fast fingers.
[ ] [ ] [ ] [ ] [ ]
For example, if focus is moved to the next element in the keyup
event, a user with fast fingers can type more than one character into the current input
. The following is excerpted from code that works OK (on desktop and android -- haven't tested with iPhone yet) but only if the user types at a normal steady speed, not quickly:
$("input").keydown(function (e) {
var $el = $(this);
switch(e.key) {
//<snip> tests for arrow keys, backspace, delete, enter, etc </snip>
// in a `switch` block
default:
if ((/[A-Z]/i.test(e.key)) && e.key.length === 1) {
// allow overtype of existing value with new one
// without having to delete the value first
$el.val(e.key);
// to require a value to be deleted before it can be
// replaced with a new value, use this:
// if (! $el.val()) $el.val(e.key);
} else {
$el.val('');
}
break;
}
}
$("input").keyup(function (event) {
var $el = $(this);
//<snip> tests for backspace, delete, enter key etc </snip>
setTimeout(() => $el.next('input').focus().click(), 0);
$el.blur();
});
jquery
mobile
keydown
timing
keyup
0 Answers
Your Answer