Search code examples
jqueryselectioncontenteditablerangy

Preserve caret position in contenteditable when unwrapping element?


I have this problem which I have tried to show in this jsFiddle. I have contenteditable in which is simple html - just text and one <B> element. My question is about situation when the caret is somewhere inside <B> element and user hits "X" key. Then the <B> element is succesfully unwrapped, but caret changes position and moves to the beginning of the unwrapped <B> element.

I want the caret to not change its position and stay in the samoe position. Is it possible ? Preferrably solution by using Rangy library ?

The code is simplified for purpose of this question:

<div id="contenteditable" contenteditable="true">
  text text text text <b>bold bold bold</b> text text text
</div>

$(document).ready(function(){
  $('#contenteditable').bind('keyup', function(e){
    if (e.which == 88) {
      $('#contenteditable').find('b').contents().unwrap();
    }
  });
});​

Solution

  • I would suggest storing the caret position as a character index within the text inside your contenteditable element. The same code that I linked to in an answer to a recent question of yours would do:

    https://stackoverflow.com/a/10682429/96100