How to Detect CTRL+V in Javascript

In this tutorial, you will learn how to detect ctrl+v in javascript. Whenever a user wants to paste something in the input field, he can either use the context menu by doing right click on the webpage or press CTRL and V keys simultaneously on their keyboard.

Any user interaction on a webpage using keyboard triggers keyboard events.  There are 3 keyboard events keyup, keypress, and keydown. In the case of keyboard events, the event object contains certain properties which can help in detecting which key is pressed by the user.

In the following example, we have 2 textarea elements. We will enter a random text in the first textarea element.  Then, we will copy it and paste it using CTRL + V in the second textarea element. When the text is pasted, we will simply show an alert message.  Please have a look over the code example and steps given below.

HTML & CSS

  • We have 3 elements in the HTML file (div, and 2 textarea). The div element is just a wrapper for the rest of the elements.
  • The placeholder text for the first textarea element is “Enter Text” and for the second textarea element, it is “Paste Text”.
  • We have done some basic styling using CSS and added the link to our style.css stylesheet inside the head element.
  • We have also included our javascript file script.js with a script tag at the bottom.
<!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">
    <title>Document</title>
</head>
<body>
    
    <div class="container">
        <textarea cols="30" rows="5" placeholder="Enter Text"></textarea>
        <textarea cols="30" rows="5" placeholder="Paste Text"></textarea>
    </div>

    <script src="script.js"></script>
</body>
</html>
.container {
    display: flex;
    flex-direction: column;
    align-items: center;
}

textarea {
    margin-top: 20px;
}

Javascript

  • We have selected the second textarea element using the document.querySelector() method and stored it in txtArea variable.
  • We have attached the keyup event listener to the textarea element.
  • In the event handler function, we are using ctrlKey and key properties of the event object to detect whether the user has pressed CTRL and V simultaneously to paste text in the second textarea element. If yes, then we will display an alert message with a text containing “Hello World” using alert() method.
let txtArea = document.querySelector('textarea+textarea');

txtArea.addEventListener('keyup', (e) =>{
    if(e.ctrlKey && e.key =='v'){
        alert('Hello World');
    }
});