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

C

charly

Greetings,

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 :
<html>
<head>
<script>
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;

}
else
textEl.value = text;
}
</SCRIPT>
</head>
<body>

<form NAME="aForm">
<textarea NAME="aTextArea" ROWS="5" COLS="80" WRAP="soft"
ONSELECT="storeCaret(this);"
ONCLICK="storeCaret(this);"
ONKEYUP="storeCaret(this);"Kibology for all.
All for Kibology.
</textarea>
<br>
<input TYPE="text" NAME="aText" SIZE="80" VALUE="Scriptology">
<br>
<input TYPE="button" VALUE="insert at caret"
ONCLICK="insertAtCaret(this.form.aTextArea,
this.form.aText.value);"</form>

</body>
</html>
But I cannot the char's position

any ideas ?
 
I

Ivo

charly said:
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.
HTH
Ivo
 
C

charly

Works great with Ie. Didn't know about the createTextRange,
parentElement stuff

Thank you very much !
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,226
Members
46,815
Latest member
treekmostly22

Latest Threads

Top