How to detect backspace key in JavaScript | Example code

You can use addEventListener or onkeydown property to detect a used pressed backspace key or no in JavaScript. Where Backspace key keycode is 8 and key is “Backspace”.

Example of detect backspace key in JavaScript

HTML example code, popup alert box if use press the backspace key in input box.

Using addEventListener

<!DOCTYPE html>
<html>

<body>

  <input type="text" id="txtbox">

  <script>

    var input = document.getElementById('txtbox');
    
    input.addEventListener('keydown', function(event) {
      const key = event.key;
      if (key === "Backspace") {
        alert(key);
      }
    });
  </script>

</body>
</html>

Using .onkeydown

More recent and much cleaner: use event.key

<!DOCTYPE html>
<html>

<body>

  <input type="text" id="txtbox">

  <script>

    var input = document.getElementById('txtbox');

    input.onkeydown = function() {
      const key = event.key;
      if (key === "Backspace") {
        alert(key);
      }
    };
  </script>

</body>
</html>

Output:

detect backspace key in JavaScript

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

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.