Set text-cursor position in a textarea
you can use these 2 functions below written by Jamie Munro (setSelectionRange()
& setCaretToPos()
):
function setSelectionRange(input, selectionStart, selectionEnd) {
if (input.setSelectionRange) {
input.focus();
input.setSelectionRange(selectionStart, selectionEnd);
}
else if (input.createTextRange) {
var range = input.createTextRange();
range.collapse(true);
range.moveEnd('character', selectionEnd);
range.moveStart('character', selectionStart);
range.select();
}
}
function setCaretToPos (input, pos) {
setSelectionRange(input, pos, pos);
}
EXAMPLE:
for example, if you want to set the caret at the end of your textarea you can have this:
setCaretToPos(document.getElementById('textarea'), -1);
After refocusing the textarea with txtarea.focus()
, add this line:
txtarea.selectionEnd= end + 7;
That will set the cursor seven positions ahead of where it was previously, which will take [b][/b]
into account.
Example
document.getElementById('bold').addEventListener('click', boldText);
function boldText() {
var txtarea = document.getElementById("editor_area");
var start = txtarea.selectionStart;
var end = txtarea.selectionEnd;
var sel = txtarea.value.substring(start, end);
var finText = txtarea.value.substring(0, start) + '[b]' + sel + '[/b]' + txtarea.value.substring(end);
txtarea.value = finText;
txtarea.focus();
txtarea.selectionEnd= end + 7;
}
#editor_area {
width: 100%;
height: 10em;
}
<button id="bold">B</button>
<textarea id="editor_area"></textarea>
if you are using jquery you can do it like this.
$('textarea').prop('selectionEnd', 13);