Open In App

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.

Approach

Example: This example shows the use of the above-explained approach.






<!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:




Article Tags :