Sometimes, we want to detect backspace and del on input event with JavaScript.
In this article, we’ll look at how to detect backspace and del on input event with JavaScript.
How to detect backspace and del on input event with JavaScript?
To detect backspace and del on input event with JavaScript, we can check the keydown event object’s key property.
For instance, we write
input.addEventListener("keydown", ({ key }) => {
if (["Backspace", "Delete"].includes(key)) {
return false;
}
});
to add a keydown event listener to the input with input.addEventListener.
In the event listener callback, we check if the key property is 'Backspace' or 'Delete'.
If it is, then we return false to stop the default action.
Conclusion
To detect backspace and del on input event with JavaScript, we can check the keydown event object’s key property.