I am attempting to program a jQuery file with event listeners to respond to several keyboard events, including Ctrl+Z, Ctrl+Y, Ctrl+X, and more. Currently, I've started working on the undo and redo functions, and both work fine in Firefox 49, but in Chrome 53 they both seem incorrect (yet predictable).
Firefox 49 handles both undo and redo perfectly correctly, but Chrome 53 seems to listen for different ASCII key codes than Firefox does. On top of that, Chrome only decides to handle that ASCII code after typing Ctrl+Z twice, as it seems to ignore the first attempt completely.
Below is my snippet of code:
$(document).on('keypress', ':input', function(event) {
if(event.ctrlKey && (event.which === 88 || event.which === 120)){ // cut handled in another event
// don't transmit Ctrl+x or Ctrl+X
return;
}
else if(event.ctrlKey && (event.which === 89 || event.which === 121)){
// todo handle Ctrl+y or Ctrl+Y (redo)
}
// Google Chrome
else if(event.which === 25){ // Chrome seems to want me to use ASCII code 25
// todo handle Ctrl+y or Ctrl+Y (redo)
}
// undo done similar to redo
}
My two questions are, as follows:
Why does Chrome not want to use the same ASCII codes as Firefox? Both are the latest versions at the time of posting, yet both seem to want to handle basic operations differently.
How would I get Chrome to perform the undo/redo the first time the key shortcuts are used, instead of having to type them in twice, which obviously is not intended.
Thank you in advance.
As written in the comment, use keyup instead of keypress and you'll receive the 'correct' codes.
In order to understand the difference between keydown and keypress, it is useful to understand the difference between a "character" and a "key". A "key" is a physical button on the computer's keyboard while a "character" is a symbol typed by pressing a button. In theory, the keydown and keyup events represent keys being pressed or released, while the keypress event represents a character being typed. The implementation of the theory is not same in all browsers.
You could examine the difference with this small script
$(document).on('keyup', ':input', function(event) {
// switching to keyup will return the same keycode
// in all browers
console.log(e.which);
});