This repository has been archived by the owner on Jan 15, 2022. It is now read-only.
forked from marcuswestin/Caret-position
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathget.js
52 lines (47 loc) · 1.58 KB
/
get.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
/**
* @module caret-position/get
*
* Adoption from code at
* http://blogs.nitobi.com/alexei/wp-content/uploads/2008/01/getcaretselection3.js
*
* @return the caret position in a text field
*/
module.exports = function (input) {
var docObj = input.ownerDocument,
result = { start:0, end:0, caret:0 };
if (navigator.appVersion.indexOf("MSIE")!=-1) {
if (input.tagName == "TEXTAREA") {
if (input.value.charCodeAt(input.value.length-1) < 14) {
input.value = input.value.replace(/34/g,'') + String.fromCharCode(28);
}
var range = docObj.selection.createRange(),
rangeCopy = range.duplicate();
rangeCopy.moveToElementText(input);
rangeCopy.setEndPoint('StartToEnd', range);
result.end = input.value.length - rangeCopy.text.length;
rangeCopy.setEndPoint('StartToStart', range);
result.start = input.value.length-rangeCopy.text.length;
result.caret = result.end;
if (input.value.substr(input.value.length-1) == String.fromCharCode(28)) {
input.value = input.value.substr(0, input.value.length-1);
}
} else {
var range = docObj.selection.createRange(),
rangeCopy = range.duplicate();
result.start = 0 - rangeCopy.moveStart('character', -100000);
result.end = result.start + range.text.length;
result.caret = result.end;
}
} else {
var isNumber = input.type === 'number'
if (isNumber) input.type = 'text'
result.start = input.selectionStart;
result.end = input.selectionEnd;
result.caret = result.end;
if (isNumber) input.type = 'number'
}
if (result.start < 0) {
result = { start:0, end:0, caret:0 };
}
return result;
};