Capturing ctrl+z key combination in javascript

Paul Johnston picture Paul Johnston · Apr 15, 2013 · Viewed 91.1k times · Source

I am trying to capture ctrl+z key combination in javascript with this code:

<html>
<head>
    <title>Untitled Document</title>
</head>
<body>

    <script type='text/javascript'>
        function KeyPress(e) {
            var evtobj = window.event? event : e


            //test1 if (evtobj.ctrlKey) alert("Ctrl");
            //test2 if (evtobj.keyCode == 122) alert("z");
            //test 1 & 2
            if (evtobj.keyCode == 122 && evtobj.ctrlKey) alert("Ctrl+z");
        }

        document.onkeypress = KeyPress;
    </script>

</body>
</html>

Commented line "test1" generates the alert if I hold down the ctrl key and press any other key.

Commented line "test2" generates the alert if I press the z key.

Put them together as per the line after "test 1 & 2", and holding down the ctrl key then pressing the z key does not generate the alert as expected.

What is wrong with the code?

Answer

zerkms picture zerkms · Apr 15, 2013
  1. Use onkeydown (or onkeyup), not onkeypress
  2. Use keyCode 90, not 122

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.)