Open In App

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

Improve
Improve
Like Article
Like
Save
Share
Report

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.

Approach

  • Event Listener: The script adds an keydown event listener to the document.
  • Element Access: It accesses the HTML element with the id “myDiv” using document.getElementById('myDiv').
  • Ctrl+C Check: It checks if the Ctrl key is pressed and the key pressed is either ‘c’ or ‘C’.
  • Ctrl+V Check: It checks if the Ctrl key is pressed and the key pressed is either ‘v’ or ‘V’.
  • Div Content Update: Depending on the key combination detected, it updates the content <div> accordingly.

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">
    <title>Clear Div Content with Copy and Paste</title>
</head>
 
<body>
 
    <!-- Example div with content -->
    <div id="myDiv">
        This is some content.
    </div>
 
    <script>
        // JavaScript to clear the content
        // of the div on Ctrl+C or Ctrl+V
        document.addEventListener('keydown', function (event) {
            let myDiv = document.getElementById('myDiv');
 
            // Check for Ctrl+C (copy) or Ctrl+V (paste)
            if (event.ctrlKey && (event.key === 'c'
            || event.key === 'C')) {
                myDiv.innerHTML = 'ctrl + C key pressed';
            }
            if (event.ctrlKey && (event.key === 'v'
            || event.key === 'V')) {
                myDiv.innerHTML = 'ctrl + V key pressed';
            }
        });
    </script>
 
</body>
 
</html>


Output:

CTRL



Last Updated : 28 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads