3
votes

I used the code sample below to disable ctrl + c and ctrl + v and it works. I used similar mechanics to disable ctrl + z (undo) in the browser but it doesn't work.

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

$('body').keydown(function(e) {
  if (e.keyCode == 17 || e.keyCode == 91) {
    ctrlDown = true;
  };
}).keyup(function(e) {
  if (e.keyCode == 17 || e.keyCode == 91) {
    ctrlDown = false;
  };
});

$("body").keydown(function(e){
  if ((ctrlDown && e.keyCode == zKey) || (ctrlDown && e.keyCode == vKey) || (ctrlDown && e.keyCode == cKey)) {
    e.preventDefault();
    return false;
  }
});
1
This code prevents Ctrl+Z, Ctrl+C and Ctrl+V in my tests. jsfiddle.net/xg3z2p5o - Bill Effin Murray
What is the point of this? Your code won't make the Edit menu disappear, so none of these actions will be disabled. You're just making a nuisance of yourself. - r3mainer
doesn't make sense using multiple handlers for the same event either - charlietfl
@squeamishossifrage It's for a code battle game. There is a feature in the code editor to shuffle the code ten times. It's a lot harder/slower to click undo in edit menu than to ctrl+z for undo. - Lina
@squeamishossifrage You don't know their use case. Stack Overflow is a question and answer site NOT a question and argue site. There are many valid reasons. The goal of the site is to answer the question. I have a specific use case where CTRL+Z is causing undesired behavior. So this question is valid for me. - 1.21 gigawatts

1 Answers

0
votes

I can see from testing that the if condition in your $("body").keydown handler isn't firing. While ctrlDown does get set to true, for some reason your series of conditions isn't firing. I don't think storing key codes and ctrl state in the global scope is going to be a great approach.

Rather than a separate handler testing for ctrl usage, it'd be easier to test just within the "z" keydown handler for whether Ctrl (or Meta i.e. command, to be Mac-compatible as well) is being used. The event object has Boolean properties ctrlKey and metaKey for just such occasions. So your code would be:

$("body").keydown(function(e){
  var zKey = 90;
  if ((e.ctrlKey || e.metaKey) && e.keyCode == zKey) {
    e.preventDefault();
    return false;
  }
});

This is still not quite as robust as it could be, since you'd want to only check metaKey on Mac and check ctrl on Linux/Windows to handle a few edge cases where someone might press "Meta + Z" (does that do anything in Windows?), but it's close. It works on my Mac.


A caution—& you've probably already considered this—that disabling OS-level keyboard shortcuts can be really dangerous. It messes with user expectations in a bad way. If you're overriding to do something similar in a big browser app, that makes perfect sense, though. Be careful!