Web Hosting Talk







View Full Version : Finding cursor position in textarea


BurakUeda
10-24-2007, 05:46 AM
In Internet Explorer, I need to find current cursor position in a textarea. Nothing is selected, nothing will be replaced or added. I just want to know where the cursor is, (e.g. if cursor is in left of 12th char, I need to retrieve 12).

Google gave me some results about finding start and end positions of selected text. Or cursor position in a text field. But couldn't find anything about this.

Again, this is IE only.

Any help?

Thanks.

triXtyle
10-24-2007, 05:51 AM
Edit: http://weblogs.asp.net/skillet/archive/2005/03/24/395838.aspx

cheers :beer:

BurakUeda
10-24-2007, 06:29 AM
Thanks trix, but I need the char position. I also saw that website but it finds the char position by calculating the pixel position and works only in fixed width fonts.

triXtyle
10-24-2007, 07:14 AM
http://www.csie.ntu.edu.tw/~b88039/html/jslib/caret.html
This might work :)

cheers :beer:

BurakUeda
10-24-2007, 08:21 AM
Finally I found it!

Here is the code:

var area = document.getElementById("textareaID"); //This is your textarea
area.focus(); // We need to put focus on it, or this won't work.
var c = "{{#$%&{}"; // This is some weird text that unlikely you will have in your textbox.
var sel = document.selection.createRange(); // Create a selection range...
var sel2 = sel.duplicate(); // ...and duplicate it
sel2 .moveToElementText(area); // move the selection to your textarea
sel.text = c; //add the weird text to your selection.
pos = (sel2.text.indexOf(c)); // get the position of your weird text, which is basicly the cursor position.