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

后端 未结 12 664
失恋的感觉
失恋的感觉 2020-12-17 09:27

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

12条回答
  •  再見小時候
    2020-12-17 10:07

    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.

    Now:

    • 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.

提交回复
热议问题