Javascript – Which keycode for escape key with jQuery

javascriptjquery

I have two functions. When enter is pressed the functions runs correctly but when escape is pressed it doesn't. What's the correct number for the escape key?

$(document).keypress(function(e) { 
    if (e.which == 13) $('.save').click();   // enter (works as expected)
    if (e.which == 27) $('.cancel').click(); // esc   (does not work)
});

Best Answer

Try with the keyup event:

$(document).on('keyup', function(e) {
  if (e.key == "Enter") $('.save').click();
  if (e.key == "Escape") $('.cancel').click();
});