Trigger Ctrl+z & Ctrl+y keypress on button click
Asked Answered
C

2

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;
Calgary answered 3/12, 2015 at 10:15 Comment(2)
Remove on from Event type text, usage should be like jQuery.Event("keydown")Alrzc
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)Heterosexual
T
9

You can try this:

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

function doRedo(){
  document.execCommand('redo', false, null);
}
Tricot answered 6/9, 2016 at 20:30 Comment(0)
P
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;
Plasmagel answered 8/11, 2021 at 8:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.