How can I “undo” the programmatic insertion of text into a textarea?

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 insertion of text and revert the textarea to its previous state?



I think the easiest approach to leverage browser's undo stack instead of capturing events.

To do this you need to use different codes for different browsers. Luckily out of all major browsers only Firefox has a different approach.

// Opera 8.0+
var isOpera = (!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;

// Firefox 1.0+
var isFirefox = typeof InstallTrigger !== 'undefined';

// Safari 3.0+ "[object HTMLElementConstructor]" 
var isSafari ='Constructor') > 0 || (function(p) {
  return p.toString() === "[object SafariRemoteNotification]";
})(!window['safari'] || safari.pushNotification);

// Internet Explorer 6-11
var isIE = /*@[email protected]*/ false || !!document.documentMode;

// Edge 20+
var isEdge = !isIE && !!window.StyleMedia;

// Chrome 1+
var isChrome = !! && !!;

var position = 0;

// text to anser
var text = 'Inserted Text';

// Just for fun :)
if (isFirefox)
  text = "  __ Firefox __ ";
else if (isIE)
  text = "  __ IE __ ";
else if (isEdge)
  text = "  __ Edge __ ";
else if (isSafari)
  text = "  __ Safari __ ";
else if (isOpera)
  text = "  __ Opera __ ";
else if (isChrome)
  text = "  __ Chrome __ ";

/* Adding text on click based on browser */
jQuery(".addText").on("click", function() {
  if (isFirefox) {
    // Firefox
    var val = jQuery(".textArea").val();

    var firstText = val.substring(0, position);
    var secondText = val.substring(position);

    jQuery(".textArea").val(firstText + text + secondText);
  } else {

    var val = jQuery(".textArea").val();

    jQuery(".textArea")[0].selectionStart = position;
    jQuery(".textArea")[0].selectionEnd = position;

    document.execCommand('insertText', false, text);

jQuery(".textArea").on("focusout", function(e) {
  position = jQuery(this)[0].selectionStart;
textarea {
  padding: 10px;
  font-family: Calibri;
  font-size: 18px;
  line-height: 1.1;
  resize: none;
.addText {
  padding: 5px 15px;
  transition: all 0.5s;
  border: 1px solid black;
  border-radius: 2px;
  background-color: #169c16;
  width: 70px;
  margin: 10px 0;
  color: white;
  cursor: pointer;
.addText:hover {
  background-color: #2776b9;
<script src=""></script>
<textarea name='textArea' class='textArea' rows="7" cols="50">Suspendisse convallis, metus at laoreet congue, sapien dui ornare magna, a porttitor felis purus a ipsum. Morbi vulputate erat rhoncus, luctus neque ut, lacinia orci. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis
  egestas. Fusce aliquam, nulla nec fringilla ultrices, ipsum lectus maximus nisl, ut laoreet purus lectus eget nisl. Duis blandit cursus nulla. Vestibulum consectetur, nunc non viverra condimentum, neque neque tincidunt diam, nec vestibulum neque nisi
  ac sem. Integer aliquam a leo id laoreet. Mauris ultrices mauris lorem, eu hendrerit odio volutpat ut. Nam eget hendrerit metus.</textarea>
<div class='addText'>
  Add Text

Tested on:

  • FF: 50
  • Chrome: 55
  • Edge 38
  • Safari: 5.1
  • Opera: 42

You need to insert the text in a special way so the user can use the normal undo/redo behaviour.

var textEvent = document.createEvent('TextEvent');

textEvent.initTextEvent('textInput', true, true, null, "new text");


Save the original value of the textarea in its data:

var $textarea = $('textarea');

$('button').on('click', function () {
    var val = $textarea.val();

    $'old-val', val).val(val + ' some text');

If you want an array of data (as @ahren suggested), use this:

var $textarea = $('textarea');

$('button').on('click', function () {
    var val = $textarea.val();

    if ( ! $'old-val')) {
        $'old-val', []);


    $textarea.val(val + ' some text');
$("#target").keypress(function(event) {
  if ( event.which == 'Z' && first press == 'Cmd' && second press == 'Ctrl') {//check for key press
    text.value = defaultValueForTextField

That should be what you are looking for. First and Second press will need to be saved as you want combo presses. You will indeed need to save a default text value though.


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(<type>, <details>);
  var b1 = <textbox>.dispatchEvent(e1);


  • <type> represents the event type such as keydown, keypress or keyup
  • <details> represents the object having event details such key, code
  • <textbox> represents the target textbox on which we want to trigger the event

Here 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):

  1. explicitOriginalTarget is different than originalTarget when I simulate the events; and when I type in textbox both have same value
  2. rangeParent and rangeOffset values are null / 0 when I type in textbox; and when I simulate the events they have some values
  3. isTrusted 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:


Even if this question is a year ago old, I want to share my way too.

You can do it like this:

    $(function () {

  // Check to see if an array is not already defined.
  if (!$('#t').data('old-val')) {

    // If the check returns True we proceed to create an array in old-val.
    $('#t').data('old-val', []);


  // Get the current content value.
  inputValue = $('#t').val();

  // Push it to the old-val array.

  // We start with a current array position of 0.
  curArrPos = 0;

  $('#c').click(function () {
    // Append a string to the #t.
    $('#t').val(' ==this is the 2nd appended text==');

    // Save the current content value.
    inputValue = $('#t').val();
    // Push it to the array.
    // Increment current array position.


  $('#b').click(function () {
    // Append a string to the #t.
    $('#t').val(' ==this is the 1st appended text==');

    // Save the current content value.
    inputValue = $('#t').val();
    // Push it to the array.
    // Increment current array position.


  $('#undo').click(function () {
    // First check that the old-val array length is greater than 1 (It's the initial position. No need undoing to a blank state) and current array position greater than 0 (for the same reason).
    if ($('#t').data('old-val').length > 1 && curArrPos > 0) {

      // Set current #t value to the one in the current array position, minus one.
      // Minus one gets you to the previous array position (ex. current=5; previous= current - 1 = 4).
      $('#t').val($('#t').data('old-val')[curArrPos - 1]);

      // Decrease current array position, because we effectively shifted back by 1 position.

  $('#redo').click(function () {
    if (currentArrayPos < $('#c').data('old-val').length - 1) {

      $('#t').val($('#t').data('old-val')[curArrPos + 1]);

      // Increase current array position, because we effectively shifted forward by 1 position.



Here's a fiddle if you want to experiment with it

I wrote the code like this for good comprehension, but you should of course write the actual code better and less verbose than this.


Concrete libs and technologies strongly depends on your stack.

There are 2 general ways i can think of instantly.

First: Save the previous state in your controller. Hook into the shortcut and replace the content to the previous state. If other modifications are made delete the hook. More or less your 2013 approach

This is a quick way and does not play nice if you want a stack with more than a one time edit history.

Second: Watch the textinput and save the state on a stack periodicly. Hook into the shortcut. (Take over the whole process). This is a cleaner way because your modification is conceptually the same as user modifications.

This could be pretty straightforward with a redux/flux architecture

For capturing cmd/ctrl+z you could look into

If you elaborate a bit more about your stack/requirements i would be happy to expand this answer.


The simplest way seems this:

  • save previous textarea contents on button click, in an attribute of DOM textarea itself.
  • intercept keyboard at the BODY level (you don't know where the focus will be when and if Ctrl-Z is hit)
  • (optional) also intercept as many events from different objects as needed: input, keyPress, and so on, also at the BODY level.


  • when the user clicks the button, old contents is saved and a custom "dirty" attribute of textarea is set to true
  • if the user hits Ctrl-Z or Cmd-Z, the undo routine is straightforward (in jQuery that would be $('#idOfTextarea').val($('#idOfTextarea').attr('prevContents')); . The undo routine also clears the "dirty" attribute so that undo is not called twice.
  • (optional) if the user alters another field, clicks somewhere else etc., the dirty attribute of the textarea is also cleared, and the change becomes undoable.
  • (optional) objects with an undo function of their own can/must stop the event propagation to avoid other undo's having two effects.

You may want, or not, to also intercept onChange on the textarea. If onChange fires and dirty is not set, that is the initial button click and may be ignored. Otherwise it might indicate that the user has added some changes of his own to the text clicked in. In that case you may want to disable the undo to preserve those changes, or ask the user for confirmation.


You can do like this,


<div id="text-content">
 <textarea rows="10" cols="50"></textarea>
   <input type="button" name="Insert" value="Insert" />


var oldText = [],ctrl=false;
          var text = oldText.length+1;
          var textAreaText = $('textarea').val();
          textAreaText +=text;
            if(e.which == 17){ ctrl = true;}
         var c = e.which;
         if(c == 17){ ctrl = false;}
         if(ctrl==true && c==90 ){
            var text = '';
               text += ele;

You can also check and experiment with the fiddle.


Add html first and you can use keypress event for undo

you can try here also here

            <input type="text" class="reset actor_input" name="actor" value="add actors"></input>

            <input type="text" name="actors"></input>

            <div class="found_actors"></div>

            <div id="add" class="button_content">ADD</div>

            <div id="undo" class="button_content">UNDO</div>

            <div class="actors_list"><textarea readonly style="resize: none;" rows="20" cols="20" name="actors-list"></textarea></div>


**then add jquery **

    var items = [];

$("#add").click(function() {
    // Push the new actor in the array

       if( e.which === 90 && e.ctrlKey ){
         console.log('control + z'); 
         if (items.length > 0) {
        // remove last element of the array

populate = function() {

you can try here

this is working for me


There are alot of applicable answers here that would work for what you want. Here is what I would do in your circumstance. This allows for the changing of a text variable that you would most likely use, you can set it or the user can set it with another field, etc.

codepen here

the jist of it would be something like this.

  function deployText(){
    var textArray = [];
    var textToAdd = 'let\'s go ahead and add some more text';
    var textarea = $('textarea');
    var origValue = textarea.text();

    $('button').on('click', function(e){

    $(document).on('keypress', function(e){
      var zKey = 26;
      if(e.ctrlKey && e.which === zKey){

    function removePreviousText(){
      if(textArray.length > 1){

Here's a short and non-jQuery solution which works in Firefox too (undo isn't possible in any way there)

// Solution
function insertText(textarea, text) {
	if (!document.execCommand('insertText', false, text)) {

// Demo code to add text on click
const textarea = document.querySelector('textarea');
textarea.onclick = () => insertText(
<textarea>Click in here to add text</textarea>

I also packaged this up as an npm module, improving consistency across browsers.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.