Capturing ctrl+z key combination in javascript

  1. Use onkeydown (or onkeyup), not onkeypress
  2. Use keyCode 90, not 122
function KeyPress(e) {
      var evtobj = window.event? event : e
      if (evtobj.keyCode == 90 && evtobj.ctrlKey) alert("Ctrl+z");
}

document.onkeydown = KeyPress;

Online demo: http://jsfiddle.net/29sVC/

To clarify, keycodes are not the same as character codes.

Character codes are for text (they differ depending on the encoding, but in a lot of cases 0-127 remain ASCII codes). Key codes map to keys on a keyboard. For example, in unicode character 0x22909 means 好. There aren’t many keyboards (if any) who actually have a key for this.

The OS takes care of transforming keystrokes to character codes using the input methods that the user configured. The results are sent to the keypress event. (Whereas keydown and keyup respond to the user pressing buttons, not typing text.)

Leave a Comment