Capturing "Delete" Keypress with jQuery
Asked Answered
B

5

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.

Beaulahbeaulieu answered 12/7, 2009 at 15:30 Comment(1)
WIth Jquery: $(document).keyup( function(e) { if(e.key == 'Backspace' || e.key == 'Delete') { ... } });Protein
T
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.

Tomfoolery answered 12/7, 2009 at 15:34 Comment(4)
keyup would be do the job better.Peephole
@Peephole no, the user expects feedback on keydown, not keyup. All text editors perform actions when a key is pressed, not when it's released.Tomfoolery
@PhilippeLeybaert In my case program can't catch the last pressed char.Peephole
same as atilkan, so i use keyupSeka
J
87
$('html').keyup(function(e){
    if(e.keyCode == 46) {
        alert('Delete key released');
    }
});

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

Jambeau answered 27/7, 2012 at 10:21 Comment(3)
It should be alert('Delete Key Released').Milline
if somebody uses keypress instead of keyup has suggested by Tod then you would get keycode == 46 event against . key (dot). but it works well with keyUp. ThanksParenthesis
As pointed out in another answer, the .keyCode is deprecated.Hedwighedwiga
C
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.

Craven answered 1/11, 2012 at 10:39 Comment(1)
It should be e.keyCode and not e.KeyCodeParameter
E
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

Eliath answered 3/12, 2017 at 1:36 Comment(0)
N
2

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

 $(document).keyup(function(e){
   if(e.key === "Backspace") {
    alert('Delete key/ backspace');
   }
 });
Noahnoak answered 9/3, 2021 at 1:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.