I have a <textarea>
element that I listen for certain key presses from. Like if a user types the Tab key, I prevent the default action of changing focus and add the tab character at the correct position.
The problem is when users press one of the keys I listen for, undo goes a little haywire. How do I get the undo/redo functionality to work? I thought about listening for ctrl/cmd-z and ctrl/cmd-shift-z key presses, recording everything, and processing the undos/redos, but then the edit and context menu choices wouldn't work...
You can see by typing letters with tabs and enters and then trying to undo and redo:
const textarea = document.querySelector('textarea')
textarea.addEventListener('keydown', function (event) {
if (event.key == "Tab") {
event.preventDefault()
const cursor = textarea.selectionStart
textarea.value = textarea.value.slice(0, cursor) + '\t' + textarea.value.slice(textarea.selectionEnd)
textarea.selectionStart = textarea.selectionEnd = cursor + 1
} else if (event.key == "Enter") {
event.preventDefault()
const cursor = textarea.selectionStart
textarea.value = textarea.value.slice(0, cursor) + '\n' + textarea.value.slice(textarea.selectionEnd)
textarea.selectionStart = textarea.selectionEnd = cursor + 1
}
})
<textarea cols="50" rows="20"></textarea>