Skip to content

Instantly share code, notes, and snippets.

@fnicollier
Created December 11, 2012 13:12
Show Gist options
  • Save fnicollier/4258461 to your computer and use it in GitHub Desktop.
Save fnicollier/4258461 to your computer and use it in GitHub Desktop.
Insert text into a textarea at cursor position
//http://www.scottklarr.com/topic/425/how-to-insert-text-into-a-textarea-where-the-cursor-is/
function insertAtCaret(areaId,text) {
var txtarea = document.getElementById(areaId);
var scrollPos = txtarea.scrollTop;
var strPos = 0;
var br = ((txtarea.selectionStart || txtarea.selectionStart == '0') ?
"ff" : (document.selection ? "ie" : false ) );
if (br == "ie") {
txtarea.focus();
var range = document.selection.createRange();
range.moveStart ('character', -txtarea.value.length);
strPos = range.text.length;
}
else if (br == "ff") strPos = txtarea.selectionStart;
var front = (txtarea.value).substring(0,strPos);
var back = (txtarea.value).substring(strPos,txtarea.value.length);
txtarea.value=front+text+back;
strPos = strPos + text.length;
if (br == "ie") {
txtarea.focus();
var range = document.selection.createRange();
range.moveStart ('character', -txtarea.value.length);
range.moveStart ('character', strPos);
range.moveEnd ('character', 0);
range.select();
}
else if (br == "ff") {
txtarea.selectionStart = strPos;
txtarea.selectionEnd = strPos;
txtarea.focus();
}
txtarea.scrollTop = scrollPos;
}
@tihoho
Copy link

tihoho commented Jun 4, 2018

thanks.

@barinascode
Copy link

thanks brother, me sirvio burda vladi1000 :v

@firatoltulu
Copy link

Thanks.

@basitiyidir
Copy link

Thanks.

@meigesir
Copy link

Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment