Listen to undo/redo event in contenteditable div
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 otherinputType
values: https://w3c.github.io/input-events/#interface-InputEvent-Attributes- Browser compatibility for
beforeinput
: https://caniuse.com/#feat=mdn-api_htmlelement_beforeinput_event
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>