125

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?

Hulk1991
  • 3,079
  • 13
  • 31
  • 46
Paul Johnston
  • 1,253
  • 2
  • 9
  • 4

10 Answers10

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

Avatar
  • 14,622
  • 9
  • 119
  • 198
zerkms
  • 249,484
  • 69
  • 436
  • 539
  • 1
    Thanks, that works. Why doesn't onkeypress and keyCode 122 work? – Paul Johnston Apr 15 '13 at 02:59
  • How to preventDefault() instead of alert in your solution please? I m testing for Ctrl+ t. – Surendra Jnawali Apr 17 '13 at 06:09
  • @SJnawali: I'm not sure it's possible for `ctrl+t` – zerkms Apr 17 '13 at 06:25
  • 4
    _why does keyCode 122 doesn't work?_ well, `122` is for **F11** key :) – Baby Feb 20 '14 at 08:30
  • 7
    @PaulJohnston Because a **key** code isn't the same as a **character** code. 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.) – Aidiakapi May 14 '14 at 15:13
  • @PaulJohnston I believe you have to use `keydown` because all the other events are too late. By that I mean the browser intercepts the command and performs the native undo, whereas on keydown, the browser hasn't yet taken note of the event – Luke Madhanga Aug 11 '15 at 13:15
  • @casperOne Actually you are wrong... please check this answer http://stackoverflow.com/a/15310690. acc to this the keydown gets triggered for all keys but on the other hand keypress triggers only when a character is pressed. – orangespark Nov 21 '16 at 11:38
  • dont forget about event.metaKey – help Aug 24 '22 at 07:03
  • 1
    please note **window.event** is deprecated. – Normal Aug 28 '22 at 20:05
116

For future folks who stumble upon this question, here’s a better method to get the job done:

document.addEventListener('keydown', function(event) {
  if (event.ctrlKey && event.key === 'z') {
    alert('Undo!');
  }
});

Using event.key greatly simplifies the code, removing hardcoded constants. It has support for IE 9+.

Additionally, using document.addEventListener means you won’t clobber other listeners to the same event.

Finally, there is no reason to use window.event. It’s actively discouraged and can result in fragile code.

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
lazd
  • 4,468
  • 3
  • 23
  • 17
  • 3
    Furthermore, I would add that `KeyboardEvent.keyCode` is now deprecated since a couple years ago. The best way to capture all browsers is checking `e.key` first and then fallback to `e.keyCode`. Or [you can use this polyfill](https://github.com/cvan/keyboardevent-key-polyfill/) – Yes Barry Sep 19 '19 at 13:38
  • do not forget about event.metaKey – help Aug 24 '22 at 07:04
10

Ctrl+t is also possible...just use the keycode as 84 like

if (evtobj.ctrlKey && evtobj.keyCode == 84) 
 alert("Ctrl+t");
Organiccat
  • 5,633
  • 17
  • 57
  • 104
6
$(document).keydown(function(e){
  if( e.which === 89 && e.ctrlKey ){
     alert('control + y'); 
  }
  else if( e.which === 90 && e.ctrlKey ){
     alert('control + z'); 
  }          
});

Demo

Jose Ricardo Bustos M.
  • 8,016
  • 6
  • 40
  • 62
Mehtab
  • 453
  • 5
  • 17
4
document.onkeydown = function (e) {
    var special = e.ctrlKey || e.shiftKey;
    var key = e.charCode || e.keyCode;
  console.log(key.length);
  if (special && key == 38 || special && key == 40 ) { 
    // enter key do nothing
    e.preventDefault();
  }        
}

here is a way to block two keys, either shift+ or Ctrl+ key combinations.

&& helps with the key combinations, without the combinations, it blocks all ctrl or shift keys.

3

90 is the Z key and this will do the necessary capture...

function KeyPress(e){
     // Ensure event is not null
     e = e || window.event;

     if ((e.which == 90 || e.keyCode == 90) && e.ctrlKey) {
         // Ctrl + Z
         // Do Something
     }
}

Depending on your requirements you may wish to add a e.preventDefault(); within your if statement to exclusively perform your custom functionality.

Andrii Omelchenko
  • 13,183
  • 12
  • 43
  • 79
JDandChips
  • 9,780
  • 3
  • 30
  • 46
0

The KeyboardEvent.keyCode is deprecated (link) think about using KeyboardEvent.key instead (link).

So, the solution would be something like this.

if (e.key === "z" && e.ctrlKey) {
   alert('ctrl+z');
}
Aymen Fezai
  • 93
  • 2
  • 11
-1

enter image description here

You can actually see it all in the KeyboardEvent when you use keydown event

-1
document.addEventListener('keydown', function(event) {
if ((event.ctrlKey || event.metaKey) &&event.shiftKey && event.key === 'z') {
  console.log('Redo!');
}else if ((event.ctrlKey || event.metaKey) && event.key === 'z') {
  console.log('Undo!');
}else if ((event.ctrlKey || event.metaKey) && event.key === 'c') {
  console.log('Copy!');
}else if ((event.ctrlKey || event.metaKey) && event.key === 'v') {
  console.log('Paste!');
}else if ((event.ctrlKey || event.metaKey) && event.key === 'x') {
  console.log('Cropp!');
}

});

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Mar 21 '23 at 14:03
-3

Use this code for CTRL+Z. keycode for Z in keydown is 90 and the CTRL+Z is ctrlKey. check this keycode in your console area

 $(document).on("keydown", function(e) {
       console.log(e.keyCode, e.ctrlKey);
       /*ctrl+z*/
       if (e.keyCode === 90 && e.ctrlKey) { // this is confirmed with MacBook pro Monterey on 1, Aug 2022
       {
          //your code here
       }
    });
Karthikeyan Ganesan
  • 1,901
  • 20
  • 23