I'm creating an application with undo/redo functionality, and would like to utilize keyboard shortcut functionality to trigger this behavior, e.g. cmd+Z
Per the MDN documentation, it appears possible to bind to the "Undo" key event.
My current code looks like this.
document.onkeydown = checkKey;
function checkKey(e) {
if (e.key === "Undo") {
e.preventDefault();
undo();
}
But it's still triggering the browser's default undo action (which in the case of Arc goes to a different tab).
Elsewhere on StackOverflow, I see some old solutions involving using keyup
and keydown
for specific event.keycode
s, which works for me... but per MDN those are deprecated and I'd like to avoid it if possible. Wondering if there's a better, modern solution using e.key
Thank you in advance!
document.addEventListener("keydown", checkKey);
function checkKey(e) {
// Check for the appropriate key combination for undo (e.g., Command/Ctrl + Z)
if ((e.metaKey || e.ctrlKey) && e.key === "z") {
e.preventDefault();
undo();
}
}