8

I have provided two separates button for Ctrl+z and Ctrl+y. I want the Ctrl+z and Ctrl+y functionality to be performed on the click of a button.

To achieve this, I am trying to trigger Ctrl+z and Ctrl+y on button click but they are not getting triggered.

The code I have written so far:

case "undo":
    var press = jQuery.Event("onkeydown");
    press.ctrlKey = true;
    press.keyCode = 90;
    jQuery(".excellentableEditSpread").trigger(press);
    break;

case "redo":
    var press = jQuery.Event("onkeydown");
    press.ctrlKey = true;
    press.keyCode = 89;
    jQuery(".excellentableEditSpread").trigger(press);
    break;
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
Akanksha
  • 81
  • 1
  • 4
  • Remove `on` from Event type text, usage should be like `jQuery.Event("keydown")` – Satpal Dec 03 '15 at 10:18
  • 1
    If you plan to trigger the browser "undo/redo" behavior I guess you can't do it using keyevent trigger. (same as you can't fill an input text with emulated keyevent) – Hacketo Dec 03 '15 at 10:32

2 Answers2

9

You can try this:

function doUndo(){
  document.execCommand('undo', false, null);
}

function doRedo(){
  document.execCommand('redo', false, null);
}
parismiguel
  • 586
  • 6
  • 16
0

This will work likectrl+z or ctrl+y press.

case "undo":
    document.dispatchEvent(new KeyboardEvent('keydown', {'key': 'z', 'ctrlKey': true}));
    break;

case "redo":
    document.dispatchEvent(new KeyboardEvent('keydown', {'key': 'y', 'ctrlKey': true}));
    break;
Azam Alvi
  • 6,918
  • 8
  • 62
  • 89