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.
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
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With