-
Notifications
You must be signed in to change notification settings - Fork 19
/
jquery.plugin.clipboard.js
105 lines (71 loc) · 3.89 KB
/
jquery.plugin.clipboard.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
94
95
96
97
98
99
100
101
102
103
104
105
/*
* @author Niklas von Hertzen <niklas at hertzen.com>
* @created 14.6.2011
* @website http://hertzen.com
*/
(function( $ ){
$.fn.clipboard = function(options) {
var defaults = {
prepend: null, // content to prepend to copy selection
append: null, // content to append to copy selection
disable:false, // disable copying for element
oncopy: function(content){} // callback on copy event
};
var options = $.extend({},defaults,options);
$(this).each(function(i,el){
el.oncopy = function(e,b){
if (options.disable){
return false;
}
if (window.clipboardData && document.selection) { // Internet Explorer
var s = document.selection;
var r = s.createRange();
var t = r.htmlText;
if (options.prepend!==null){
t = options.prepend + t;
}
if (options.append!==null){
t = t + options.append;
}
options.oncopy(t);
if (window.clipboardData.setData ("Text", t)){
return false;
}
}else {
// the rest (which don't support clipboardData)
var s = window.getSelection();
var r = s.getRangeAt(0);
if (options.append!==null){
var a = $('<span style="display: inline-block; width: 0px; height: 0px; overflow: hidden; zoom: 1;" />').html(options.append);
var tmpr = s.getRangeAt(s.rangeCount-1);
var rangeAppend = document.createRange();
rangeAppend.setStart(tmpr.endContainer,tmpr.endOffset);
rangeAppend.insertNode(a[0]);
rangeAppend.setEnd(a[0], a[0].childNodes.length);
window.setTimeout(function(){
$(a).remove();
},0);
}
if (options.prepend!==null){
var n = $('<span style="display: inline-block; width: 0px; height: 0px; overflow: hidden; zoom: 1;" />').html(options.prepend);
r.insertNode(n[0]);
var range = document.createRange();
range.setStart(n[0], 0);
range.setEnd(n[0], n[0].childNodes.length);
s.addRange(range);
window.setTimeout(function(){
$(n).remove();
},0);
}
s.removeAllRanges();
s.addRange(r);
if (options.append!==null){
s.addRange(rangeAppend);
}
options.oncopy(s.toString());
}
};
});
return this;
}
})( jQuery );