How to make a contenteditable div reversible after change made with js?
Asked Answered
E

1

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 ?

Eurythermal answered 21/8, 2013 at 2:44 Comment(1)
This isn't normally true: Ctrl-Z works fine in contenteditable unless you've disabled the shortcut in your key event handling. See jsfiddle.net/68MwfAdvancement
N
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.

Ngo answered 21/8, 2013 at 2:48 Comment(2)
+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.Kimber
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 and note that there's plenty of places which triggers the "save snapshot" action.Sondra

© 2022 - 2024 — McMap. All rights reserved.