131

When using the example code from the jQuery documentation for the keypress event handler, I'm unable to capture the Delete key. The snippet below is going to log 0 when the Delete key is pressed in FireFox:

$(document).keypress(function(e) {
    console.log(e.which);       
});

Seems there's gotta be a way to capture the Delete key, but it's an ambiguous term so Google isn't proving to be much help with it.

H. Pauwelyn
  • 13,575
  • 26
  • 81
  • 144
Shane H
  • 3,263
  • 5
  • 26
  • 30
  • WIth Jquery: `$(document).keyup( function(e) { if(e.key == 'Backspace' || e.key == 'Delete') { ... } });` – Avatar Nov 12 '22 at 17:29

5 Answers5

216

You shouldn't use the keypress event, but the keyup or keydown event because the keypress event is intended for real (printable) characters. keydown is handled at a lower level so it will capture all nonprinting keys like delete and enter.

Philippe Leybaert
  • 168,566
  • 31
  • 210
  • 223
87
$('html').keyup(function(e){
    if(e.keyCode == 46) {
        alert('Delete key released');
    }
});

Source: javascript char codes key codes from www.cambiaresearch.com

Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
Tod Palin
  • 887
  • 6
  • 2
39

Javascript Keycodes

  • e.keyCode == 8 for backspace
  • e.keyCode == 46 for forward backspace or delete button in PC's

Except this detail Colin & Tod's answer is working.

csonuryilmaz
  • 1,715
  • 24
  • 24
27

event.key === "Delete"

More recent and much cleaner: use event.key. No more arbitrary number codes!

NOTE: The old properties (.keyCode and .which) are Deprecated.

document.addEventListener('keydown', function(event) {
    const key = event.key; // const {key} = event; ES6+
    if (key === "Delete") {
        // Do things
    }
});

Mozilla Docs

Supported Browsers

Gibolt
  • 42,564
  • 15
  • 187
  • 127
2

You can track the delete/ backspace key with jQuery as follow:

 $(document).keyup(function(e){
   if(e.key === "Backspace") {
    alert('Delete key/ backspace');
   }
 });
Danhdds
  • 149
  • 2
  • 8