Categories
JavaScript Answers

How to detect Ctrl+V, Ctrl+C using JavaScript?

Spread the love

To detect Ctrl+V, Ctrl+C using JavaScript, we listen for keypresses on the window.

For instance, we write

window.onkeypress = (evt) => {
  const c = evt.keyCode;
  const ctrlDown = evt.ctrlKey || evt.metaKey;

  if (ctrlDown && evt.altKey) {
    return true;
  } else if (ctrlDown && c === 67) {
    // c
    return false;
  } else if (ctrlDown && c === 86) {
    // v
    return false;
  } else if (ctrlDown && c === 88) {
    // x
    return false;
  }
  return true;
};

to set window.onkeypress to a function that checks for various keys.

We check for ctrl or meta key press with evt.ctrlKey || evt.metaKey.

And then we check for keyCode for the 2nd key if ctrlDown is true.

If keyCode is 67, then c is pressed.

If keyCode is 86, then v is pressed.

If keyCode is 88, then x is pressed.

We return false if any of those are true to stop the behavior of copy and paste.

Otherwise, we return true.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *