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 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.