Skip to content

How to detect backspace key in JavaScript | Example code

  • by

You can use addEventListener or onkeydown property to detect a used pressed backspace key or not 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 the user presses the backspace key in the 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 or suggestions 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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading