0

Here is the demo. For example, I want to get a b after I key down a, like this:

const text = document.getElementById('text');
text.addEventListener('keydown', (e) => {
  if (e.key === 'a') {
    e.preventDefault();
    const start = e.target.selectionStart;
    const end = e.target.selectionEnd;
    e.target.value = `${e.target.value.substring(0, start)}b${e.target.value.substring(end)}`;

    e.target.selectionStart = start + 1;
    e.target.selectionEnd = start + 1;
  }
})
<textarea id="text"></textarea>

But I cannot undo (control+z) the input after I type a, as the b is just staying there and I cannot go to the state before.

My question is how to store the state before I type a? So like before (without the event listener), I can press control+z to undo my input.

cloned
  • 6,346
  • 4
  • 26
  • 38
cesc
  • 65
  • 1
  • 4
  • Or is there a way to store a state every after a period of time? So I can undo to history state after setting this event listener. – cesc Mar 18 '21 at 03:02
  • This HTML isn’t valid. Tags cannot be opened after ``, and `` is missing. – Sebastian Simon Mar 18 '21 at 03:04
  • 1
    Possible [duplicate](https://google.com/search?q=site%3Astackoverflow.com+js+cannot+undo+after+programmatically+changing+text) of [Is it possible to edit a text input with javascript and add to the Undo stack?](https://stackoverflow.com/q/27027833/4642212) or [How can I “undo” the programmatic insertion of text into a textarea?](https://stackoverflow.com/q/13597007/4642212). Unfortunately, this is currently difficult to achieve in a cross-browser and cross-platform way. – Sebastian Simon Mar 18 '21 at 03:08
  • @Simon, I am sure it is valid on my browser. Thank you for the links and they are very helpful. I will try them one by one. I think it's ok even if it just works fine on Chrome. ( But what do you mean by saying it is difficult in a cross-browser/platform environment? – cesc Mar 18 '21 at 03:19
  • If you read the comments in these links, there’s a lot of discussion about incompatibility with Firefox and a linked bug report; you can also visit the [documentation for `document.execCommand`](https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand), see that it’s deprecated, and has had various incompatibilities in all browsers and platforms. See also [`execCommand()` is now obsolete, what's the alternative?](/q/60581285/4642212) _“I am sure it is valid on my browser”_ — It may work, but it isn’t _valid_. You can [validate your HTML](https://html5.validator.nu/). – Sebastian Simon Mar 18 '21 at 03:21
  • Well. Anyway I just want to give a minimal demo and avoid other useless information here. It's not from the real codes. Thank you anyway for these possible solutions – cesc Mar 18 '21 at 03:25

0 Answers0