So, I'm playing around with the (AWESOME) Rangy text selection package. I'm editing text inside of a span
with contenteditable=true
, with the goal of having a text input element which allows individual styling of each character. Let me stress that last point -- each character should be in its own span. This works fine if I don't need to preserve the styling from one keystroke to the next -- I just do something like
var newHTML = field.innerText.split('').map(function(c){
return ('<span class="letter">'+c+'</span>');
}).join('');
$(field).empty().append(newHTML);
and use Rangy's (1.3) saveCharacterRange()
function to restore the selection, and it's all good.
The problem comes when I've already styled some of those spans, and I delete one, replacing it with new text. I want newly inserted text to be unstyled, but instead it gets inserted into the preceding (or following, if the selection is at the beginning) span. I've tried to work around this by explicitly collapsing the selection's region after (or before) the focusNode, but it seems to not allow the endContainer
(or startContainer
) to be anything other than a text node... I've even verified that I can create a text range which collapses where I want it, but the selection object's setSingleRange()
seems to collapse back around the text node.
I tried inserting a new node and placing the selection wholly inside it, which does work when the new node has content in it before calling insertNode()
, but I obviously can't be inserting extra content between each character...
Here's a fiddle demonstrating what I'm talking about. Thanks for any help!