1

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.keycodes, 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!

1
  • Are you having a problem with your custom code not getting executed when you use e.key === "Undo"? Or is it that the default browser Undo action cannot be prevented? Commented Jan 18, 2024 at 5:56

1 Answer 1

0
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();
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Disappointed there isn't a way to utilize the actual 'e.key === "Undo"' value, since this feels like its intended purpose... but accepting the answer since it works for me and avoids deprecated e.keycode .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.