forked from apm1467/jQuery.Custom-Caret
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjquery.custom-caret-1.1.js
67 lines (55 loc) · 2.4 KB
/
jquery.custom-caret-1.1.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
(function ($) {
$.fn.customCaret = function(options) {
var settings = $.extend({
caretID: 'caret',
callback: null
}, options);
function getCaretPosition(element) {
var caretPosition = 0;
var doc = element.ownerDocument || element.document;
var win = doc.defaultView || doc.parentWindow;
var sel;
if (typeof win.getSelection != "undefined") {
sel = win.getSelection();
if (sel.rangeCount > 0) {
var range = win.getSelection().getRangeAt(0);
var preCaretRange = range.cloneRange();
preCaretRange.selectNodeContents(element);
preCaretRange.setEnd(range.endContainer, range.endOffset);
caretPosition = preCaretRange.toString().length;
}
} else if ( (sel = doc.selection) && sel.type != "Control") {
var textRange = sel.createRange();
var preCaretTextRange = doc.body.createTextRange();
preCaretTextRange.moveToElementText(element);
preCaretTextRange.setEndPoint("EndToEnd", textRange);
caretPosition = preCaretTextRange.text.length;
}
return caretPosition;
}
return this.each(function() {
$(this).on("keydown keyup click focus", function() {
var caret = "<span id='" + settings.caretID + "'></span>";
var sel = window.getSelection();
if (sel.toString() != "") {
return;
}
var caretPosition = getCaretPosition($(this).get(0));
var content = $(this).text();
var output = content.substr(0, caretPosition) + caret + content.substr(caretPosition);
$(this).html(output);
var range = document.createRange();
range.setStart($(this).get(0).childNodes[0], caretPosition);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
});
$(this).focusout(function() {
$(this).html($(this).text());
});
if ($.isFunction(settings.callback)) {
settings.callback.call(this);
}
});
};
}(jQuery));