View Full Version : cursor positioning within a text area

08-23-2002, 02:30 PM
Could anyone tell me if and how it is possilbe to return the character position within a <textarea> When either moving the arrow keys, and clicking anywhere within the textarea with the mouse?

Cheers Pete

Here is the code I have currently, this just returns the currentcharacter position as you type.

NOTE: the submit button doesn't do anything. It is just there for layout purposes at the moment


<form method="POST">
<table border="0" cellspacing="0" cellpadding="0">
<td width="100%" colspan="2">
<textarea rows="12" name="charcount" onkeyup="return countit(this)" cols="60" wrap="virtual"></textarea>
<td valign="top" width="35%">Current Character Position:</td>
<td><div id="displaycount" size="20">&nbsp;&nbsp;</div></td>
<td align=left><input type="submit" name="submitMsg" value="Submit"></td>

<script language="JavaScript">

function countit(what){

08-23-2002, 05:22 PM
In Mozilla, it is as easy as event.rangeOffset to get the caret/selection offset (event is the argument passed to your event handlers).

IE requires some ugly TextRange work that I don't have handy.

08-23-2002, 06:34 PM
In ie you can use:

function docjslib_getRealTop(imgElem) {
yPos = eval(imgElem).offsetTop;
tempEl = eval(imgElem).offsetParent;
while (tempEl != null) {
yPos += tempEl.offsetTop;
tempEl = tempEl.offsetParent;
return yPos;

to find the absolute position of an object. Just find the cursor position and subtract the abs pos.

In case you don't know how to get the cursor position in ie:

function mmove() {
xpos = event.clientX+document.body.scrollLeft;
ypos = event.clientY+document.body.scrollTop;
window.status = xpos+" - "+ypos;

08-23-2002, 08:30 PM
x_goose_x, it seems to me they wanted caret offset in a textarea? (maybe I misread...)

08-23-2002, 08:44 PM

08-23-2002, 11:10 PM
Sorry. I'm out to lunch