Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the event.keyCode of the delete key?

$('body').keypress(function(event){

     if(event.keyCode == 46){console.log('Delete Key Pressed')}; //does not work

     if(event.keyCode == 32){console.log('SPACE BAR')}; //works
})

Why doesn't the delete key show up in THIS FIDDLE ?

like image 204
Squirrl Avatar asked Jan 21 '14 03:01

Squirrl


2 Answers

Use keydown and modern JS!

document.addEventListener("keydown", function(event) {
    if (event.key === "Delete") {
        // Do something
    }
});

Modern style, lambda + destructuring

document.addEventListener("keydown", ({key}) => {
    if (key === "Delete") {
        // Do something
    }
})
like image 160
Gibolt Avatar answered Sep 20 '22 15:09

Gibolt


Instead of keypress, use the keyup or keydown event: keypress is meant for PRINTABLE characters, whereas keydown will capture non-printing key presses including delete, backspace, and return. http://jsfiddle.net/5cNTn/9/

$('body').keydown(function(event){
    var letter = String.fromCharCode(event.which); 
    if(event.keyCode == 32){console.log('SPACE BAR');}
    if(event.keyCode == 46){console.log('Delete Key Pressed');}
    console.log(event); 
    console.log(event.keyCode); 
 });
like image 20
Max Avatar answered Sep 17 '22 15:09

Max