-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
jquery.clipboard-modifier.js
93 lines (79 loc) · 2.8 KB
/
jquery.clipboard-modifier.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/**
* JavaScript Clipboard Modifier
*
* @author Matej Lednár
*
* @param {Object} $ - jQuery
* @returns {undefined}
*/
(function ($) {
$.fn.clipboardModifier = function (data) {
var pasted = false;
var copied = false;
var lastFocus = null;
var clipboard;
var newValue = "";
function pasteAction(e) {
if (data) {
clipboard = data.clipboard ? data.clipboard : data;
} else {
clipboard = {};
}
var before = clipboard.before ? clipboard.before : "";
var after = clipboard.after ? clipboard.after : "";
var callback = clipboard.callback ? clipboard.callback : function (text) {
return text
};
var inputField;
var copiedText = "";
// get clipboard data - only text support
if (window.clipboardData && window.clipboardData.getData) { // IE
copiedText = window.clipboardData.getData('Text');
} else if (e.clipboardData && e.clipboardData.getData) {
copiedText = e.clipboardData.getData('text/plain');
}
if (copiedText == "") {
return;
}
if (pasted) {
pasted = false
return;
} else {
lastFocus = document.activeElement;
pasted = true;
// change clipboard
inputField = document.createElement("input");
// selected text bug fix (remove white spaces) and paste it again - Firefox issue
copiedText = copiedText.replace(/^\s+|\s+$/g, '');
if (copied) {
newValue = before + (callback ? callback(copiedText) : copiedText) + after;
} else {
newValue = copiedText;
}
document.body.appendChild(inputField);
inputField.value = newValue;
inputField.select();
try {
document.execCommand("copy");
document.body.removeChild(inputField);
} catch (ex) {
console.warn("Copy to clipboard action failed.", ex);
}
try {
lastFocus.focus();
document.execCommand("paste");
} catch (ex) {
console.warn("Paste action failed.", ex);
}
copied = false;
}
return this;
}
function copyAction(e) {
copied = true;
pasted = false;
}
document.addEventListener("paste", pasteAction);
document.addEventListener("copy", copyAction);
};
}(jQuery));