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.

1146 views

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:

Type something:
Log:

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:

Type something:
Log:

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:

  1. Some websites are blocking devtools with malicious JavaScript, so here is how to stop that without disabling JavaScript.
  2. We can not handle HTTP POST data from JavaScript, but we can still access the data while it is in the HTML form.
  3. getElementById should be used to select unique elements in a HTML document. Selected elements can be manipulated with JavaScript.
  4. Should you use querySelector or getElementById?; querySelector is more flexible, and able to perform more complex selections.

More in: JavaScript Tutorials