Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 5 of 5
  1. #1
    Regular Coder
    Join Date
    Jun 2002
    Location
    The Netherlands
    Posts
    217
    Thanks
    0
    Thanked 0 Times in 0 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
    jkd
    jkd is offline
    Senior Coder jkd's Avatar
    Join Date
    May 2002
    Location
    metro DC
    Posts
    3,163
    Thanks
    1
    Thanked 18 Times in 18 Posts
    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.

  • #3
    jkd
    jkd is offline
    Senior Coder jkd's Avatar
    Join Date
    May 2002
    Location
    metro DC
    Posts
    3,163
    Thanks
    1
    Thanked 18 Times in 18 Posts
    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

  • #4
    Regular Coder
    Join Date
    Jun 2002
    Location
    The Netherlands
    Posts
    217
    Thanks
    0
    Thanked 0 Times in 0 Posts
    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.

  • #5
    jkd
    jkd is offline
    Senior Coder jkd's Avatar
    Join Date
    May 2002
    Location
    metro DC
    Posts
    3,163
    Thanks
    1
    Thanked 18 Times in 18 Posts
    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.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •