How to cancel keydown with JavaScript?

Sometimes, we want to cancel keydown with JavaScript.

In this article, we’ll look at how to cancel keydown with JavaScript.

How to cancel keydown with JavaScript?

To cancel keydown with JavaScript, we can call preventDefault in the keydown event handler.

For instance, we write:

document.onkeydown = (evt) => {
  const cancelKeypress = /^(13|32|37|38|39|40)$/.test(evt.keyCode.toString());
  if (cancelKeypress) {
    evt.preventDefault()
  }
};

to set document.onkeydown to a function that checks if the evt.keyCode matches any one of the numbers in the regex.

evt.keyCode is the code of the key that’s pressed.

If there’s a match, then we call evt.preventDefault to stop the default action.

Conclusion

To cancel keydown with JavaScript, we can call preventDefault in the keydown event handler.