Capturing ctrl+z key combination in javascript

JavascriptCombinationsCtrl

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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.

Solution 3 - Javascript

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

if (evtobj.ctrlKey && evtobj.keyCode == 84) 
 alert("Ctrl+t");

Solution 4 - Javascript

$(document).keydown(function(e){
  if( e.which === 89 && e.ctrlKey ){
     alert('control + y'); 
  }
  else if( e.which === 90 && e.ctrlKey ){
     alert('control + z'); 
  }          
});

Demo

Solution 5 - Javascript

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.

Solution 6 - Javascript

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.

Solution 7 - Javascript

Use this code for CTRL+Z. keycode for Z in keypress is 122 and the CTRL+Z is 26. check this keycode in your console area

 $(document).on("keypress", function(e) {
       console.log(e.keyCode);
       /*ctrl+z*/
       if(e.keyCode==26)
       {
          //your code here
       }
    });

Solution 8 - Javascript

This Plugin Made by me may be helpful.

Plugin

You can use this plugin you have to supply the key Codes and function to be run like this

simulatorControl([17,90], function(){console.log('You have pressed Ctrl+Z');});

In the code I have displayed how to perform for Ctrl+Z. You will get Detailed Documentation On the link. Plugin is in JavaScript Code section Of my Pen on Codepen.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPaul JohnstonView Question on Stackoverflow
Solution 1 - JavascriptzerkmsView Answer on Stackoverflow
Solution 2 - JavascriptlazdView Answer on Stackoverflow
Solution 3 - Javascriptchandramouli.jamadagniView Answer on Stackoverflow
Solution 4 - JavascriptMehtabView Answer on Stackoverflow
Solution 5 - JavascriptJDandChipsView Answer on Stackoverflow
Solution 6 - Javascriptnewguy12121View Answer on Stackoverflow
Solution 7 - JavascriptKarthikeyan GanesanView Answer on Stackoverflow
Solution 8 - Javascript10011101111View Answer on Stackoverflow