SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Member
    Join Date
    Feb 2005
    Posts
    5
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Saving/restoring caret position in a contentEditable div

    Ok, this is a tough one...

    I have a contentEditable element, and am using setTimeout() to call a function which changes the innerHTML of the div. Problem is that changing innerHTML moves the caret to the end of the text.

    I need to keep the caret pos so the user can keep typing. I tried storing the caret pos with
    cursorPos=document.selection.createRange().duplicate();

    And then later restoring it with cursorPos.select() - which is IE only, but it doesn't work because the content of the div gets changed between calls, and the behavior is undefined (it basically selects everything)

    Here's what I have so far: http://www.softcontest.com/sharpspell/asutype.aspx

    It's used for spell checking text as you type it, try typing something in there, and watch it get spell checked.

    Only works in IE right now, sorry Firefox folks

  2. #2
    SitePoint Member
    Join Date
    Feb 2005
    Posts
    5
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Ok, I managed to work around it, here's the solution if anyone's interested:

    Store the selection x, y:

    Code:
    cursorPos=document.selection.createRange().duplicate();
    clickx = cursorPos.getBoundingClientRect().left; 
    clicky = cursorPos.getBoundingClientRect().top;
    Restore the selection:

    Code:
    cursorPos = document.body.createTextRange();
    cursorPos.moveToPoint(clickx, clicky);
    cursorPos.select();


Bookmarks

Posting Permissions

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