-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaddTextareaTabSupport.js
45 lines (36 loc) · 1.08 KB
/
addTextareaTabSupport.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
function addTextareaTabSupport(textarea){
var tabStr = '\t';
textarea.onkeydown = function(e){
var keyCode = e.keyCode;
var caretPosition, text;
//support tab on textarea
switch(keyCode){ //tab was pressed
case 9:
text = textarea.value;
caretPosition = getCaretPosition(textarea);
textarea.value = text.substring(0, caretPosition) + tabStr + text.substring(caretPosition, text.length);
setCaretPosition(textarea, caretPosition + tabStr.length);
return false;
break; case 9:
}
}
function getCaretPosition(textarea){
return textarea.selectionStart;
}
function setCaretPosition(textarea, position){
textarea.selectionStart = position;
textarea.selectionEnd = position;
textarea.focus();
}
function hasSelection(textarea){
return textarea.selectionStart !== textarea.selectionEnd;
}
function getSelectedText(textarea){
return textarea.value.substring(textarea.selectionStart, textarea.selectionEnd);
}
function setSelection(textarea, start, end){
textarea.selectionStart = start;
textarea.selectionEnd = end;
textarea.focus();
}
}