Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to trigger an event when three keyboards are pressed at the same time in Javascript

I’m writing code to execute a specific function when the ctrl + shift + z key is pressed. When I press two keys at the same time, it works fine, but when I press three keys, the event does not occur. Below is the code I wrote.

try1:

 document.onkeydown = function (e) { 

        if (e.ctrlKey && e.key === 'z') {  // It works
            undo()  // ctrl+ z
           
        }
        else if (e.ctrlKey && e.shiftKey && e.key==='z' ) { //It doesn't work
            redo(); //ctrl + shift + z
        }
    }

try2:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

document.onkeydown = function (e) { // 
        var ctrl, shift,z
        console.log(e.key)
        switch (e.key) {
            case 'Control':
                ctrl = true;
                break;
            case 'Shift':
                shift = true;
                break;
            case 'Z':
                z = true;
                break;
   
            }
        if (ctrl&&shift&&z) redo()
  }

Neither of these will work if you’re typing on three keyboards.

How to make it work when ctrl+shift+z is pressed

>Solution :

Change the order of the conditions, as the first condition is always true if the second is true, causing the code for the second condition to never execute.

document.onkeydown = function(e) {
    if (e.ctrlKey && e.shiftKey && e.key === 'Z') {
        undo()
    } else if (e.ctrlKey && e.key === 'Z') {
        redo();
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading