7

When I delete some text in the contenteditable div in mistake, I can reverse it with Ctrl + z.

But after I made some change with javascript. I can't use Ctrl + z to reverse to previous change.

For example, when I add node to the selected text ,like <p>or <h1>, I could not reverse the content to previous change. jsfiddle.net/NfGM3/ (bad coding because I am new to window.getSelection())

I use div instead of textarea because I want to add some node into the content.

So, how can I make it reversible in contenteditable div after change made with js ?

Radian Jheng
  • 667
  • 9
  • 20
  • 1
    This isn't normally true: Ctrl-Z works fine in contenteditable unless you've disabled the shortcut in your key event handling. See http://jsfiddle.net/68Mwf/ – Tim Down Aug 21 '13 at 08:56

1 Answers1

9

What about adding a keyup event handler that will keep track of the current text after every keyup. You can then trap Ctrl+Z and revert back to the previous content if you detect that Ctrl+Z have been pressed. You could potentially keep revisions in an array to support a series of Ctrl+Z operations.

mx0
  • 6,445
  • 12
  • 49
  • 54
TGH
  • 38,769
  • 12
  • 102
  • 135
  • 3
    +1, except perhaps worth handling something other than keyup (happens too often, array gets too big, too many steps to undo). IMO: keyup triggers like a 1000ms settimeout (always assigned to the same variable so there is no more than one running), with a callback to push current state into array. Result: any consecutive keystrokes typed less than 1s apart create only one history snapshot, not one per keystroke. – Oleg Aug 21 '13 at 03:16
  • 2
    Good (usable) undo manager (because this is what you mean to implement) is not as simple to implement as you're thinking about it. Check e.g. CKEditor's [undoManager](https://github.com/ckeditor/ckeditor-dev/blob/master/plugins/undo/plugin.js) and note that there's plenty of places which triggers the "save snapshot" action. – Reinmar Aug 22 '13 at 08:14