12

Is there a way to listen on all the ways a user could trigger an undo on a contenteditable div? For example when the user hits Control+Z, Right-click -> Undo, or in the file menu Edit -> Undo.

I'm not looking for undo/redo algorithms or implementations, just the ability to listen to the event and overwrite the behavior.

Craig Gidney
  • 17,763
  • 5
  • 68
  • 136
jhchen
  • 14,355
  • 14
  • 63
  • 91

3 Answers3

5

You can get event.inputType of input event. Check for "historyUndo" / "historyRedo":

var div = document.getElementById("mydiv");
div.addEventListener("input", function(e) {
  switch(e.inputType){
    case "historyUndo": alert("You did undo"); break;
    case "historyRedo": alert("You did redo"); break;
  }
});
<div id="mydiv" contenteditable="true">Hello world!</div>

In recent browsers, you can cancel the event using the beforeinput event (not in Firefox yet):

var div = document.getElementById("mydiv");
div.addEventListener("beforeinput", function(e) {
  switch(e.inputType){
    case "historyUndo": e.preventDefault(); alert("Undo has been canceled"); break;
    case "historyRedo": e.preventDefault(); alert("Redo has been canceled"); break;
  }
});
<div id="mydiv" contenteditable="true">Hello world!</div>

References:

Motla
  • 1,092
  • 12
  • 19
1

Well, the Ctrl+Z/Y is possible, but I don't know about the Right-click->Undo/Redo part.

$(document).keydown(function (e) {
    var thisKey = e.which;

    if (e.ctrlKey) {
        if (thisKey == 90) alert('Undo');
        else if (thisKey == 89) alert('Redo');
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Maestro
  • 865
  • 1
  • 7
  • 24
Korikulum
  • 2,529
  • 21
  • 25
  • Already implemented the undo functionality in another way, but I thought it'd be cool to be able to do it with ctrl+z. Thanks, mate, worked like a charm. – Drew Dec 12 '13 at 19:58
-1

Control z example at How to detect Ctrl+V, Ctrl+C using JavaScript?

for rightclick you can show a div on a right click How can I capture the right-click event in JavaScript?

then when they click the undo option on the div. just put in a onclick function.

Community
  • 1
  • 1
Jared Drake
  • 982
  • 4
  • 12