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);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With