JavaScript detect backspace and delete | example code

Using keydown event and addEventListener you can detect the key, whether it is back or del in JavaScript.

Will check on document, you can also do it with input filed. Using switch statement for matching conditions.

HTML example code with vanilla JavaScript.

<!DOCTYPE html>
<html>
<body>

  <script>

    document.addEventListener("keydown", KeyCheck);  //or however you are calling your method
    function KeyCheck(event)
    {
     var KeyID = event.keyCode;
     switch(KeyID)
     {
      case 8:
      alert("backspace");
      break; 
      case 46:
      alert("delete");
      break;
      default:
      break;
    }
  }
</script>
</body>
</html>

Output:

JavaScript detect backspace and delete

event.key === “Backspace” or “Delete”

input.addEventListener('keydown', function(event) {
    const key = event.key; // const {key} = event; ES6+
    if (key === "Backspace" || key === "Delete") {
        return false;
    }
});

Do comment if you have any doubts and suggestion on this JS code.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.