Inserting content where the cursor is is sort of complicated. At least it used to be. I haven’t studied the issue in quite some time, things may have improved. The following is javascript I used for this. It’s old code, but it still works. There may be a better way now.
// edInsertContent - insert myvalue at cursor in textarea
function edInsertContent(which, myValue) {
var myField = document.getElementById(which);
//IE support
if (document.selection) {
myField.focus();
sel = document.selection.createRange();
sel.text = myValue;
myField.focus();
}
//MOZILLA/NETSCAPE support
else if (myField.selectionStart || myField.selectionStart == '0') {
var startPos = myField.selectionStart,
endPos = myField.selectionEnd,
scrollTop = myField.scrollTop;
myField.value = myField.value.substring(0, startPos)
+ myValue
+ myField.value.substring(endPos, myField.value.length);
myField.focus();
myField.selectionStart = startPos + myValue.length;
myField.selectionEnd = startPos + myValue.length;
myField.scrollTop = scrollTop;
} else {
myField.value += myValue;
myField.focus();
}
}
Thank you so much!
This really helps me a lot:
One problem left:
The tinymce editor in wordpress is not a <textarea> but only a <body> and selectionStart doesn’t work with it.
Do you have another solution for this?
Thanks,
Jonas
Sorry, no. While I thought it was likely you were referring to tinymce, there remained some doubt, so I went ahead and posted anyway, since I had the code ready to go.
There’s surely some way to get the cursor position, even if not selectionStart. It’s just a matter of finding out how. (Easier said than done, I know) The ensuing logic of my code is probably still valid though the specific methods called may change.
Hopefully if anyone has anything to add towards solving this puzzle, they’ll chime in here.