I have a textarea and a button. Clicking the button causes text to be inserted into the textarea.
Is there a way to allow a user to press Ctrl/Cmd+z to undo the inse
Here is a thought:
If we can generate the keyborad events just as if the user is typing in the textarea, then browser will automatically be able to handle Undo event. So instead of just appending / changing the value of textarea, we should try to simulate keyboard events for the text that we want to insert.
As per the documentation at MDN (links given below), we can use KeyboardEvent object to generate the events like:
var e1 = new KeyboardEvent(, );
var b1 = .dispatchEvent(e1);
Where:
represents the event type such as keydown, keypress or keyup represents the object having event details such key, code represents the target textbox on which we want to trigger the eventHere is a JSFiddle where I've tried to simulate keydown, keypress and keyup events for each character in a given string. Though its firing the appropriate event handlers, somehow the chars are not getting displayed / added to textbox.
What I've noticed is that there are some differences in the event object generated when I type a in the textbox verses when I simulate the 3 events for a using my code. The differences are (when tested in Firefox 50.1.0):
explicitOriginalTarget is different than originalTarget when I simulate the events; and when I type in textbox both have same valuerangeParent and rangeOffset values are null / 0 when I type in textbox; and when I simulate the events they have some valuesisTrusted property is true when I type in textbox; and when I simulate the events its false (For any event generated using script it will have false)MDN links: