5

When I'm inserting an html tag inside a contenteditable div I need the cursor to move outside (to the right) the new inserted element, so if I continue to type, the new text will be unformatted.

With Firefox I've found this solution is working just fine:

node = document.createElement("strong");
node.innerHTML = "test";

range.deleteContents();
range.insertNode(node);
range.collapse(false);

The variable range is set this way:

if (window.getSelection) {
    var sel = window.getSelection();
    if (sel.getRangeAt && sel.rangeCount) {
        range = sel.getRangeAt(0);
    }
}

Using the above code in webkit browsers (Chrome / Safari) put the cursor outside the new tag, but to the left.

Is there a solution for this (Chrome / Safari) and for IE support (mainly 9, optionally 8)?

Thanks

=============================================

Thanks to Tim for his advices, here's the working code:

var node = document.createElement("strong");
node.innerHTML = "test";

var space = document.createElement("span");
space.innerHTML = "\u200B";

range.insertNode(space);
range.insertNode(node);
range.collapse(false);

var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
Ted R
  • 143
  • 2
  • 7

1 Answers1

6

You need to reselect the range in non-Mozilla browsers. This will work in all major browsers except IE <= 8:

var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);

For IE <= 8, you can use a different approach. Here's another answer of mine with a complete example:

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

Community
  • 1
  • 1
Tim Down
  • 318,141
  • 75
  • 454
  • 536
  • Thanks Tim, the cursor is now moved correctly to the right, but if I type the text is formatted, so the cursor is still inside the tag – Ted R Feb 19 '13 at 12:23
  • @TedR: That's because some browsers (WebKit and IE in particular) have set ideas about where in the document the caret can be and will normalize any range you select to fit in with those ideas. The only solution is to hack around it: adding a zero-width space character after the element you're inserting, for example. It's not nice. – Tim Down Feb 19 '13 at 12:38
  • i tried similar approach of adding space to the end of the node but the cursor still doesnt move outside the element. All the subsequent inserts are inside the previous insert **bold**sa**bold** – user648929 May 01 '13 at 14:44
  • Wow this really helped, I have been searching for this solution for days!!! Thanks! – SAF Nov 27 '20 at 05:09