To ensure that the keydown
event is blocked on a textarea
for all keyboard keypresses except for ctrl+c, ctrl+v, command+c, and command+v keys.
For Mac users, utilize event.metaKey
to detect the command key.
Try copying text from the textarea using ctrl+c or pasting text inside it using ctrl+v
Stack Snippet
var textarea = document.getElementById("text");
textarea.addEventListener("keydown", function(event) {
var key = event.key;
var cmd_key = event.metaKey;
var ctrl_key = event.ctrlKey;
if ((cmd_key && key == "c") || (ctrl_key && key == "c")) {
return true;
} else if ((cmd_key && key == "v") || (ctrl_key && key == "v")) {
return true;
} else {
event.preventDefault();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post">
<h3>Text:</h3>
<textarea id="text" name="text" rows="4" cols="50">Copy this text and paste</textarea>
<br><br>
</form>