Anyway, so I was specifically looking for a way to handle the case where a user pastes content into a field using keyboard shortcuts.
Before looking at the copy, the general idea behind my approach is as follows:
- Setup a keymap that will look for `CTRL` or `CMD` and `V`
- 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
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
V exist in the specified
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:
- When a key is pressed down, checks to see if it’s `CTRL` or `CMD`.
- 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.
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.