Get Caret position (or cursor) from a textarea (and restore it)

Author Message
Fredledingue

  • Total Posts : 572
  • Scores: 2
  • Reward points : 0
  • Joined: 5/9/2005
  • Location: Europe
  • Status: offline
Get Caret position (or cursor) from a textarea (and restore it) Sunday, December 05, 2010 3:24 PM (permalink)
0
I spent the whole night setting that up.
From what I'v read other coders have spent days without finding a pallatable solution.
It was one of the thoughest coding challenge I'v met.
Everything seemed to be done to make it impossible.
Everything I found was stubbornly putting the caret at the end of the textarea, did nothing, were extremely complicated or gave an error.
I think I have found a solution with this:
Quiet brutal, I know but it works.
look here
or here:
Set objTA = document.getElementById(TextAreaId)
objTA.focus
MyTag = "!*g$" '---It can be whatever you want, but something unusual
document.selection.createRange().text = MyTag
'---We replace temporarily VbCrlf par Vblf so that 1 new line = 1 character and not 2 --- 
strTemp = Replace(objTA.innerText, VbCrlf, Vblf)
CaretPos = InStr(strTemp, MyTag)-1
'---This line can be obmitted if you change the text or the HTML of the textarea before restoring the caret---
objTA.innerText = Replace(Replace(strTemp, MyTag, ""), Vblf, VbCrlf)
'--- Add your code here
'--- Restore the position of the caret---
Set range = objTA.createTextRange()
range.collapse true 
range.moveStart "character", CaretPos
range.moveEnd "character", 0
range.select

Fred
 
#1

    Online Bookmarks Sharing: Share/Bookmark

    Jump to:

    Current active users

    There are 0 members and 1 guests.

    Icon Legend and Permission

    • New Messages
    • No New Messages
    • Hot Topic w/ New Messages
    • Hot Topic w/o New Messages
    • Locked w/ New Messages
    • Locked w/o New Messages
    • Read Message
    • Post New Thread
    • Reply to message
    • Post New Poll
    • Submit Vote
    • Post reward post
    • Delete my own posts
    • Delete my own threads
    • Rate post

    2000-2012 ASPPlayground.NET Forum Version 3.9