By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,607 Members | 1,817 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,607 IT Pros & Developers. It's quick & easy.

get a a char's position when its string is clicked

P: n/a

I got the following problem :

I have a input text which holds the following value : hello

Now, when the user click on the first l, a window.alert pops up and
prints 3.

Question : Is it possible to get the cursor's position in an input text?
Note I said input text, not a textarea.

So far, I've found this :
function storeCaret (textEl) {
if (textEl.createTextRange)
textEl.caretPos = document.selection.createRange().duplicate();

function insertAtCaret (textEl, text) {

if (textEl.createTextRange && textEl.caretPos) {
var caretPos = textEl.caretPos;
alert(caretPos.text.length - 1);
caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' '
? text + ' ' : text;

textEl.value = text;

<form NAME="aForm">
<textarea NAME="aTextArea" ROWS="5" COLS="80" WRAP="soft"
Kibology for all.
All for Kibology.
<input TYPE="text" NAME="aText" SIZE="80" VALUE="Scriptology">
<input TYPE="button" VALUE="insert at caret"


But I cannot the char's position

any ideas ?

Jul 20 '05 #1
Share this Question
Share on Google+
2 Replies

P: n/a

"charly" <ka*******> wrote in message
Is it possible to get the cursor's position in an input text?

Try this function (IE only):

function caretPos(){
var i=document.f.txt.value.length+1;
if (document.f.txt.createTextRange){
theCaret = document.selection.createRange().duplicate();
while (theCaret.parentElement()==document.f.txt &&
theCaret.move("character",1)==1) --i;
return i==document.f.txt.value.length+1?-1:i;

You 're lucky you have an input. I use this function in a textarea, and if
my cursor is at the 345th position, it takes quite a while for the while
loop on line 5 to reach the end.

Jul 20 '05 #2

P: n/a
Works great with Ie. Didn't know about the createTextRange,
parentElement stuff

Thank you very much !

Jul 20 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.