Categories
JavaScript Answers

How to capture a backspace on the keydown event with JavaScript?

Spread the love

Sometimes, we want to capture a backspace on the keydown event with JavaScript.

In this article, we’ll look at how to capture a backspace on the keydown event with JavaScript.

How to capture a backspace on the keydown event with JavaScript?

To capture a backspace on the keydown event with JavaScript, we can check the keyCode property.

For instance, we write

document.getElementById("foo").addEventListener("keydown", (event) => {
  if (event.keyCode === 8) {
    console.log("BACKSPACE was pressed");
    event.preventDefault();
  }
  if (event.keyCode === 46) {
    console.log("DELETE was pressed");
    event.preventDefault();
  }
});

to call addEventListener to listen to the keydown event.

In the event listener, we get the keyCode property.

If it’s 8, then backspace key is pressed.

And if it’s 46, the delete key is pressed.

Conclusion

To capture a backspace on the keydown event with JavaScript, we can check the keyCode property.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *