Note: this answer describes how to get the character co-ordinates of the text-cursor/caret. To find the pixel-co-ordinates, you'll need to extend this further.
The first thing to remember is that the cursor can be in three states
- a regular insertion cursor at a specific position
- a text selection that has a certain bounded area
- not active: textarea does not have focus. Has not been used.
The IE model uses the Object document.selection, from this we can get a TextRange object which gives us access to the selection and thus the cursor position(s).
The FF model/Opera uses the handy variables [input].selectionStart and selectionEnd.
Both models represent a regular ative cursor as a zero-width selection, with the left bound being the cursor position.
If the input field does not have focus, you may find that neither is set.
I have had good success with the following code to insert a piece of text at the current cursor location, also replacing the current selection, if present.
Depending on the exact browser, YMMV.
function insertAtCursor(myField, myValue) {
/* selecion model - ie */
if (document.selection) {
myField.focus();
sel = document.selection.createRange();
sel.text = myValue;
}
/* field.selectionstart/end firefox */
else if (myField.selectionStart || myField.selectionStart == '0' ) {
var startPos = myField.selectionStart;
var endPos = myField.selectionEnd;
myField.value = myField.value.substring(0, startPos)
+ myValue
+ myField.value.substring(endPos, myField.value.length);
myField.selectionStart = startPos + myValue.length;
myField.selectionEnd = startPos + myValue.length;
myField.focus();
}
// cursor not active/present
else {
myField.value += myValue;
}
Bug Note: links are not being correctly marked up in the top para.
Selection object: http://msdn.microsoft.com/en-us/library/ms535869(VS.85).aspx
TextRange object: http://msdn.microsoft.com/en-us/library/ms535872(VS.85).aspx