Skip to content

Instantly share code, notes, and snippets.

@tommcfarlin
Last active February 19, 2016 14:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tommcfarlin/b229e60fe986699e96ad to your computer and use it in GitHub Desktop.
Save tommcfarlin/b229e60fe986699e96ad to your computer and use it in GitHub Desktop.
[JavaScript] Detecting Copy and Paste in JavaScript with jQuery
/**
* Determines if the user has pasted content into the textarea.
*
* @param array keymap The array of keys that have been pressed.
* @return boolean True if the user is pasting content.
*/
var user_has_pasted_content = function( keymap ) {
return ( 0 === $.inArray( 17, keymap ) || 0 === $.inArray( 91, keymap ) ) &&
1 === $.inArray( 86, keymap );
};
// Refers to whatever element (such as a textarea) we're watching
var $elem;
$elem.on( 'keydown', function( evt ) {
// Log the keys being pressed (looking specifically for CTRL/CMD + V)
if ( ( 17 === evt.keyCode || 91 === evt.keyCode ) || 86 === evt.keyCode ) {
// We only add the keycode if it doesn't already exist in the keymap
if ( -1 === $.inArray( evt.keyCode, keymap ) ) {
keymap.push( evt.keyCode );
}
}
}).on( 'keyup', function() {
// Check to see if the key combination exists in the keymap
if ( user_has_pasted_content( keymap ) ) {
// Do your work here
// Reset the keymap for the next operation
keymap = [];
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment