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'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) {
// https://stackoverflow.com/a/55174581/288906
if (!document.execCommand('insertText', false, text)) {
textarea.setRangeText(text);
}
}
// Demo code to add text on click
const textarea = document.querySelector('textarea');
textarea.onclick = () => insertText(
textarea,
'@'
);
I also packaged this up as an npm module, improving consistency across browsers.