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

In this article, we will detect copy-paste commands Ctrl+V, and 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.
Approach: We will follow the following approach:
- HTML code: Below is the code for the file “index.html” to detect the combination of “Ctrl+C” and “Ctrl+V”.
- CSS code: The following code demonstrates the file “style.css” which is used in the above HTML file.
- Javascript code: The following demonstrates the code for the file “script.js” which is used in the above HTML file.
Example: This example shows the use of the above-explained approach.
HTML
<!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> |
CSS
.container{ display: flex; flex-direction: column; align-items: center; } textarea{ margin-top: 20px; } |
Javascript
<script> 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); </script> |
Output: Click here to check the live output.



