Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable Chrome's text input undo/redo (CTRL+Z / CTRL+Y)

i'm currently developing a web application and i encounter a problem. As you might know or not, chrome has a feature that gives <input> (especially text inputs) an "undo" function when you hit CTRL+Z and "redo" with CTRL+Y it may seem like a good feature in normal websites, but currently i'm making an image editor that also uses those keyboard shortcuts (CTRL+Z & CTRL+Y).

in my app i also have a text input, so when i change the text input's content and then hit CTRL+Z to undo the changes in my image editor, it would undo the change in the text editor instead!

here is a Codepen that would demonstrate the effect
(instruction is in the Codepen)

So in conclusion i want to remove the undo/redo function in chrome how can i do that?

like image 846
Bintang Anandhiya Avatar asked Oct 01 '16 01:10

Bintang Anandhiya


2 Answers

var ctrlDown = false;
var ctrlKey = 17, vKey = 86, cKey = 67, zKey = 90;

document.body.onkeydown = function(e) {
  if (e.keyCode == 17 || e.keyCode == 91) {
    ctrlDown = true;
  }
  if ((ctrlDown && e.keyCode == zKey) || (ctrlDown && e.keyCode == vKey) || (ctrlDown && e.keyCode == cKey)) {
    e.preventDefault();
    return false;
  }
}
document.body.onkeyup = function(e) {
  if (e.keyCode == 17 || e.keyCode == 91) {
    ctrlDown = false;
  };
};
<body>
    <input type='text' value='test' />
</body>

Does this work?

Stolen from here, found on here as a comment by @KadeHafen.

like image 122
StardustGogeta Avatar answered Oct 07 '22 00:10

StardustGogeta


You could use onkeydown event, and preventDefault.. eg.

document.onkeydown = function(e) {
  if (e.ctrlKey && e.key === 'z') {
    e.preventDefault();
    alert("CTRL + Z!");
  }
}
like image 44
Keith Avatar answered Oct 07 '22 00:10

Keith