Get backspace keycode in JavaScript | Example code

Backspace keycode is 8 and key is “Backspace”. Pop up Alert box if the user has hit either the backspace key.

Get backspace keycode in JavaScript Example

HTML example code: JavaScript detect backspace

Use event.key == Backspace

Check if the key’s code matches with the key code of Backspace.

<!DOCTYPE html>
<html>

<body>

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

  <script>

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

</body>
</html>

Use event.keyCode == 8

Check if the key pressed is Backspace keycode.

<!DOCTYPE html>
<html>

<body>

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

  <script>

    var input = document.getElementById('txtbox');
    input.onkeydown = function() {
      var key = event.keyCode || event.charCode;
      if( key == 8 ){
      alert(event.code);
    }
  };
</script>

</body>
</html>

Output:

Get backspace keycode in JavaScript

Another way – addEventListener

<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>

Do comment if you have any doubts and suggestions on this JS keycode 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.