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.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.