Skip to content

Instantly share code, notes, and snippets.

@nhatnx
Created October 1, 2020 05:13
Show Gist options
  • Save nhatnx/37ea4ab145b994bd952496cc55daf10a to your computer and use it in GitHub Desktop.
Save nhatnx/37ea4ab145b994bd952496cc55daf10a to your computer and use it in GitHub Desktop.
Prevents user from copying the text from form fields, either by copy/cut or dragging and dropping text
/* preventCopy()
* Prevents user from copying the text from form fields, either by copy/cut or dragging and dropping text.
* Binds preventDefault() to oncopy and oncut events.
* Binds event that makes all fields in selector readonly for onmousedown event. (Doesn't make target field readonly.)
* Binds event that removes readonly for onmouseup event.
* MSIE bug requires a user to click twice after readonly has been removed. Focus() doesn't work, use select().
* I specifically allowed pasting because the issue is really the copying.
* @param selector string required - jQuery selector for form field(s). As allowed by jQuery, this is typically a list of selectors in one string.
* @return void
*/
function preventCopy(selector) {
$(selector).bind("copy cut", function (e) {
e.preventDefault();
});
$(selector).bind("mousedown", function (e) {
$(selector).not($(this)).attr("readonly", "readonly")
});
$(selector).bind("mouseup click", function (e) {
$(selector).removeAttr("readonly");
if ($.browser.msie)
$(this)[0].select();
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment