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.