Skip to content

Instantly share code, notes, and snippets.

@ChristianOellers
Created April 26, 2019 12:05
Show Gist options
  • Save ChristianOellers/1f04ea3469da08de2805eb2e26901548 to your computer and use it in GitHub Desktop.
Save ChristianOellers/1f04ea3469da08de2805eb2e26901548 to your computer and use it in GitHub Desktop.
HTML form elements - Prevent copy & paste keyboard events + Custom UI behaviour example
/**
* Prevent use of 'CTRL+v' or 'CTRL+V' in form fields that must not be copied.
* This doesn't prevent browser native auto complete (e.g. double-clicking into a field) or vendor specific mobile device features.
*
* Example use case: Repeating fields for email, or password.
*
* @param {object} event Keydown event.
*/
function preventCopyPaste (event) {
'use strict';
var element;
if ( event.ctrlKey === true
&& (event.which === '118' || event.which === '86')) {
event.preventDefault();
element = $(event.target);
if (!element.hasClass('error')) {
element
.addClass('error')
.after('<span class="error">Please enter this information manually.</span>')
}
}
}
// Example use
$('#formfield')
.on('keydown', preventCopyPaste)
.on('contextmenu copy paste selectstart dragstart dragend', function (e) {
return false;
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment