Helpful Information
 
 
Category: DOM and JSON scripting
Get the caret position in a textarea?

How can I get the position of the caret in a textarea if no text is selected,and the selected text if the user has selected some text?
I believe this is done using ranges,but I dont know how.
Thanks in advance.

This is done in IE via a TextRange - I've never personally worked with it.

It goes something like

var textRange = document.selection.createRange();

Which returns a TextRange (http://msdn.microsoft.com/workshop/author/dhtml/reference/objects/obj_textrange.asp) object.

This createRange() is NOT what is described by the W3C DOM2 Traversal-Range spec, but rather just some stuff IE added.

As for NS6, NS7, Mozilla, etc (Gecko browsers), every event has a rangeOffset property, which can tell you the offset of the caret in an operation, such as a keystroke, mouseclick, etc.

You can also experiment with:

window.getSelection().getRangeAt(0).startOffset

In Gecko. :)

Actually, better solution for Gecko.

http://lxr.mozilla.org/seamonkey/source/dom/public/idl/html/nsIDOMNSHTMLInputElement.idl

As you can see from that IDL file, Gecko supports

HTMLInputElement.selectionStart :)

Thanks,I figured it out for IE but it doesnt work in Mozilla.
window.getSelection().getRangeAt(0).startOffset ; gives an error in the JavaScript console and .selectionStart returns undefined.

selectionStart only works for input elements, not textareas:

<input type="text" value="bla bla" onmouseup="alert(this.selectionStart)"/>

If you are using a textarea, it appears you'll need to make use of rangeOffset:

<textarea onmouseup="window.status=event.rangeOffset">
hello world
</textarea>

for example. :)

From some testing last night, it only appears window.getSelection() works for non-form selections.










privacy (GDPR)