How to trigger backspace event in JavaScript | Example code

Use onkeydown event to check backspace key trigger or not in JavaScript.

Trigger backspace event in JavaScript example

HTML example code have an input field, if user pressed an backspace key it will popup alert box.

Backspace key char is 8, so we will check the condition with same value.

<!DOCTYPE html>
<html>

<body>

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

  <script>

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

</body>
</html>

Output:

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