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.

502 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. getElementById should be used to select unique elements in a HTML document. Selected elements can be manipulated with JavaScript.
  2. Should you use querySelector or getElementById?; querySelector is more flexible, and able to perform more complex selections.
  3. Easily check if an element is either hovered or in focus using plain JavaScript.
  4. The Width and Height of the browser Window can be obtained through the innerWidth and innerHeight properties; these can be checked by an event handler to detect resize events.

More in: JavaScript Tutorials