-
Notifications
You must be signed in to change notification settings - Fork 1
/
jquery.insert-at-caret.js
66 lines (59 loc) · 2.39 KB
/
jquery.insert-at-caret.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
/*!
* jQuery insertAtCaret 1.2.3
* http://www.karalamalar.net/
*
* Copyright (c) 2023 Emre Erkan
* Licensed under GPLv2 or later.
* http://www.gnu.org/licenses/gpl-2.0.txt
*
* Contributors:
* [@kittsville](https://github.com/kittsville)
* [@Nils-Berghs](https://github.com/Nils-Berghs)
*
*/
(function ($, document, window, undefined) {
$.fn.insertAtCaret = function (text) {
return this.each(function () {
var input = this, scrollPos, strPosStart = 0, strPosEnd = 0, isModernBrowser = ("selectionStart" in input && "selectionEnd" in input), before, after, range, selection;
if (!((input.tagName && input.tagName.toLowerCase() === "textarea") || (input.tagName && input.tagName.toLowerCase() === "input" && input.type.toLowerCase() === "text"))) {
if (input.contentEditable) {
input.focus();
selection = document.getSelection();
if (selection.getRangeAt && selection.rangeCount) {
range = selection.getRangeAt(0);
range.deleteContents();
range.insertNode(document.createTextNode(text));
selection.collapseToEnd();
}
}
return;
}
scrollPos = input.scrollTop;
input.focus();
if (isModernBrowser) {
strPosStart = input.selectionStart;
strPosEnd = input.selectionEnd;
} else {
range = input.createTextRange();
range.moveStart('character', -input.value.length);
strPosStart = range.text.length;
}
if (strPosEnd < strPosStart) {
strPosEnd = strPosStart;
}
before = (input.value).substring(0, strPosStart);
after = (input.value).substring(strPosEnd, input.value.length);
input.value = before + text + after;
strPosStart = strPosStart + text.length;
if (isModernBrowser) {
input.setSelectionRange(strPosStart, strPosStart);
} else {
range = input.createTextRange();
range.move('character', strPosStart);
range.select();
}
input.scrollTop = scrollPos;
input.blur();
});
};
})(jQuery, document, window);