How to detect copy paste commands Ctrl+V, Ctrl+C using JavaScript ?

To detect the combination of keys with “Ctrl”, we use the ctrl property of the keydown event. It returns a “boolean” value to tell if “ctrl” is pressed or not when the key event got triggered.

Syntax:

event.ctrlKey

Return Value:

  • true: When “ctrl” was pressed.
  • false: When “ctrl” was not pressed.

HTML code: Below is the code for the file “index.html” to detect the combination of “Ctrl+C” and “Ctrl+V”.

HTML



filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content=
        "width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie-edge">
    <link rel="stylesheet" href="style.css">
</head>
  
<body>
    <div class="container">
        <textarea cols="30" row="5" 
            placeholder="Enter Text">
        </textarea>
  
        <textarea cols="30" row="5" 
            placeholder="Paste Text">
        </textarea>
    </div>
      
    <script src="script.js"></script>
</body>
  
</html>

chevron_right


CSS code: The following code demonstrates the file “style.css” which is used in the above HTML file.

.container{
   display: flex;
   flex-direction: column;
   align-items: center;
}

textarea{
   margin-top: 20px;
}

Javascript code: The following demonstrates the code for the file “script.js” which is used in the above HTML file.

Javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

document.body.addEventListener("keydown", function (ev) {
  
    // function to check the detection
    ev = ev || window.event;  // Event object 'ev'
    var key = ev.which || ev.keyCode; // Detecting keyCode
      
    // Detecting Ctrl
    var ctrl = ev.ctrlKey ? ev.ctrlKey : ((key === 17)
        ? true : false);
  
    // If key pressed is V and if ctrl is true.
    if (key == 86 && ctrl) {
        // print in console.
        console.log("Ctrl+V is pressed.");
    }
    else if (key == 67 && ctrl) {
  
        // If key pressed is C and if ctrl is true.
        // print in console.
        console.log("Ctrl+C is pressed.");
    }
  
}, false);

chevron_right


Output:

  • When Ctrl+C was pressed:
  • When Ctrl+V was pressed:

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.