-
Notifications
You must be signed in to change notification settings - Fork 0
/
jquery.caretpos.js
55 lines (55 loc) · 2.22 KB
/
jquery.caretpos.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
(function($) {
$.fn.caret = function(pos) {
var target = this[0];
var isContentEditable = target.contentEditable === 'true';
if (arguments.length == 0) {
if (window.getSelection) {
if (isContentEditable) {
target.focus();
var range1 = window.getSelection().getRangeAt(0),
range2 = range1.cloneRange();
range2.selectNodeContents(target);
range2.setEnd(range1.endContainer, range1.endOffset);
return range2.toString().length;
}
return target.selectionStart;
}
if (document.selection) {
target.focus();
if (isContentEditable) {
var range1 = document.selection.createRange(),
range2 = document.body.createTextRange();
range2.moveToElementText(target);
range2.setEndPoint('EndToEnd', range1);
return range2.text.length;
}
var pos = 0,
range = target.createTextRange(),
range2 = document.selection.createRange().duplicate(),
bookmark = range2.getBookmark();
range.moveToBookmark(bookmark);
while (range.moveStart('character', -1) !== 0) pos++;
return pos;
}
return 0;
}
if (pos == -1)
pos = this[isContentEditable ? 'text' : 'val']().length;
if (window.getSelection) {
if (isContentEditable) {
target.focus();
window.getSelection().collapse(target.firstChild, pos);
} else
target.setSelectionRange(pos, pos);
} else if (document.body.createTextRange) {
var range = document.body.createTextRange();
range.moveToElementText(target);
range.moveStart('character', pos);
range.collapse(true);
range.select();
}
if (!isContentEditable)
target.focus();
return pos;
}
})(jQuery)