4

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
  • 27,664
  • 8
  • 35
  • 57
Mister Happy
  • 124
  • 7
  • 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

3 Answers3

2

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,455
  • 6
  • 49
  • 92
1

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

Oak
  • 26,231
  • 8
  • 93
  • 152
0

In my case I still needed to allowing Ctrl+Z (and Ctrl+Y) when the text inputs are focused:

Utilizing the same strategy as Martin's answer, we can get rid of the chrome behavior of refocusing a previously focused element when there is no focus (the body is focused).


window.addEventListener("keydown", e => 
{
  if (e.target == document.body && e.ctrlKey && (e.key == "z" || e.key == "y"))
  {
    e.preventDefault();
  }
});

Firefox doesn't seem to have this same behavior so it definitely doesn't seem to be an OS behavior.

Hopefully this is still relevant to you, or can be useful to others searching in the future!

Riley
  • 37
  • 1
  • 6