Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
[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