Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Listen to undo/redo event in contenteditable div

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.

like image 542
jhchen Avatar asked Nov 10 '12 05:11

jhchen


2 Answers

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:

  • InputEvent specification and other inputType values: https://w3c.github.io/input-events/#interface-InputEvent-Attributes
  • Browser compatibility for beforeinput: https://caniuse.com/#feat=mdn-api_htmlelement_beforeinput_event
like image 90
Motla Avatar answered Oct 16 '22 00:10

Motla


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>
like image 35
Korikulum Avatar answered Oct 16 '22 01:10

Korikulum