Web Analytics Made Easy -
StatCounter Get the caret position in a textarea? - CodingForum

Announcement

Collapse
No announcement yet.

Get the caret position in a textarea?

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • 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.

  • #2
    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 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.
    jasonkarldavis.com

    Comment


    • #3
      Actually, better solution for Gecko.

      http://lxr.mozilla.org/seamonkey/sou...putElement.idl

      As you can see from that IDL file, Gecko supports

      HTMLInputElement.selectionStart
      jasonkarldavis.com

      Comment


      • #4
        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.

        Comment


        • #5
          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.
          jasonkarldavis.com

          Comment

          Working...
          X