Detecting copy and paste in JavaScript is not something that’s new to web development. How you do it may vary, though, depending on the set of tools you’re using.

Cut and Paste in JavaScript

Cut and paste, not cut and tape. And not like this.

Given I focus primarily on WordPress, the majority of the JavaScript I write uses jQuery. And though there are a number of ways you can go about doing this (which I’ll talk about later), some of them are deprecated (though they still work).

Anyway, so I was specifically looking for a way to handle the case where a user pastes content into a field using keyboard shortcuts.

Copy and Paste in JavaScript

Before looking at the copy, the general idea behind my approach is as follows:

  1. Setup a keymap that will look for `CTRL` or `CMD` and `V`
  2. When they’ve been pressed in conjunction with one another, take action

Obviously, I’ve generalized it a bit to say “take action” because what you do will vary from what I’ve done. But the general process remains the same.

The code listens for both the keydown and keyup events and uses an array I’m calling keymap to track the key codes that have been pressed. When a combination of the two has been pressed, then it will take action.

First, I defined a helper function that would look to see if the user had pasted code. The function looks to see if the key codes for both CTRL or CMD and V exist in the specified keymap:

Then I have a second block of code that’s setup on the document.ready handler. It attaches itself to an element to watch (here, $elem) does the following:

  1. When a key is pressed down, checks to see if it’s `CTRL` or `CMD`.
  2. If so, add it to the `keymap`.

Then, when a key is released, uses the function defined above to detect if the user pastes something into the element. If so, it does whatever work necessary and resets the keymap.

See below:

Again, there are a number of different ways to do this and your implementation will likely vary based on the tools, libraries, or frameworks you are using.

Secondly, there are other ways you can do this with jQuery (such as using bind to connect to certain events) but the above code seems to be the most robust across the various browsers I tested.