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
<!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 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
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); |
Output:
- When Ctrl+C was pressed:
- When Ctrl+V was pressed:


