Keydown and missing characters in JavaScript
the keydown event is not an ideal way to detect text-input by the user; instead you should consider using the input event.
Edited: 2021-02-20 17:22
There is a problem with missing characters when reading user input using the keydown event in JavaScript; the easiest solution is to use the input event instead.
The problem occurs because the users input is not registered on keydown, but rather on keyup. If you are relying on these events to record what a user types, then you are probably doing something wrong; the input event is much more suited for obtaining user input in real time.
If you for some reason can not use the input event, you can also try out the keyup event; although that is also not an ideal way to detect when a user is entering text.
The problem
If you try typing something in the editable area, you might notice that the output is one character behind compared to what you are typing.
Using keydown event:
The code for this example:
let textArea = document.getElementById("textArea");
let resultArea = document.getElementById("resultArea");
document.addEventListener('keydown', function (){
resultArea.innerHTML = textArea.innerText;
});
The Solution
The following example uses the input event instead of keydown or keyup; try typing something in the text box to see the difference.
Using input event:
The code for this example:
document.addEventListener('input', function (){
resultArea.innerHTML = textArea.innerText;
});
As you can see, the only thing that was changed was the event type used in the addEventListener function, and now the written characters appear instantaneously; another benefit is that it also supports pasting content into the input field.
Tell us what you think: