javascripteventskeyboard-shortcutsshiftctrl

Event shift key in combination


I need undo and redo in javascript.

ctrl + z = undo

ctrl + shift + z = redo

In the code described below, undo works normally but redo does not work. I noticed if it is shift.key alon then it works, if combined with others (shift.key + ctrl.key or "z") it doesn't work. Why.., or am I wrong somewhere in the code?

function isKeyPressedUndo(event) {
  var x = document.getElementById("demo");
  if (event.ctrlKey && event.key === 'z') {
    x.innerHTML = "The UNDO key was pressed!";
  } else {
    x.innerHTML = "The UNDO key was NOT pressed!";
  }
}

function isKeyPressedRedo(event) {
  var x = document.getElementById("demo");
  if (event.shiftKey && event.ctrlKey && event.key === 'z') {
    x.innerHTML += "The REDO key was pressed!";
  } else {
    x.innerHTML += "The REDO key was NOT pressed!";
  }
}
<input type="text" onkeydown="isKeyPressedUndo(event), isKeyPressedRedo(event)">

<p id="demo"></p>


Solution

  • Debugging 101: If an if statement fails, log the values you are testing with it.

    When the shift key is pressed event.key is an upper-case Z not a lower-case z.

    function isKeyPressedUndo(event) {
      var x = document.getElementById("demo");
      if (event.ctrlKey && event.key === 'z') {
        x.innerHTML = "The UNDO key was pressed!";
      } else {
        x.innerHTML = "The UNDO key was NOT pressed!";
      }
    }
    
    function isKeyPressedRedo(event) {
      var x = document.getElementById("demo");
      console.log([event.shiftKey, event.ctrlKey, event.key]);
      if (event.shiftKey && event.ctrlKey && event.key === 'z') {
        x.innerHTML += "The REDO key was pressed!";
      } else {
        x.innerHTML += "The REDO key was NOT pressed!";
      }
    }
    <input type="text" onkeydown="isKeyPressedUndo(event), isKeyPressedRedo(event)">
    
    <p id="demo"></p>