3

I have a canvas web application where I can an undo actions by pressing Ctrl+Z The application has also got text input elements

When I hit Ctrl+Z, on some occasions, the browser automatically focuses on a recently changed input. Does anyone know how to prevent this?

I'm using Chrome.

freedomn-m
  • 24,983
  • 7
  • 32
  • 55
Mister Happy
  • 104
  • 6
  • To be clear, you want to still carry out the undo/redo operation but not change the focus? If so I don't believe this is possible. It's part of the OS behaviour that the edited field regains focus. – Rory McCrossan Jun 19 '19 at 09:02
  • Mmm I was afraid of that. Thanks anyway – Mister Happy Jun 19 '19 at 09:04
  • Possible duplicate of [Capturing ctrl+z key combination in javascript](https://stackoverflow.com/questions/16006583/capturing-ctrlz-key-combination-in-javascript) – freedomn-m Jun 19 '19 at 09:20
  • 2
    You can intercept `document.onkeydown` and `return false` to disable the browser's control-z. Likely browser dependent, but worked fine for me in Chrome. Example fiddle (tweaked from the above duplicate): http://jsfiddle.net/btm8qkxL/ – freedomn-m Jun 19 '19 at 09:20

2 Answers2

1

I had the same problem, though interestingly on Windows only. Calling preventDefault() on the event solved it for me.

Oak
  • 25,332
  • 5
  • 90
  • 149
1

In regards to Oak's answer, in my case I couldn't just preventDefault() every keydown because we need the key strokes so this worked for me:

 keyHandler = (e: KeyboardEvent) => {
   switch (e.key) {
    case e.ctrlKey && 'z': {
      e.preventDefault();
      break;
    }
}

It is strange how an onBlur doesn't stop this from happening but if a user manually clicks off the input then CTRL + Z automatically doesn't call the input...

Martin Dawson
  • 7,007
  • 6
  • 42
  • 87