Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Contenteditable: move cursor outside inserted html node (webkit / ie)

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);
like image 587
Ted R Avatar asked Feb 19 '13 09:02

Ted R


1 Answers

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

like image 74
Tim Down Avatar answered Oct 21 '22 15:10

Tim Down