I have logic to insert a tag in a contenteditable div. I want to set the cursor to the start of the following element after the insertion. The code I have to do this is:
function insertNodeAtCaret(node) {
if(typeof window.getSelection !== 'undefined')
{
var sel = window.getSelection();
if(sel.rangeCount)
{
var rng = sel.getRangeAt(0);
rng.collapse(false);
rng.insertNode(node);
// The following doesn't work in Chrome or Safari
node = node.nextSibling;
rng.setEndAfter(node);
rng.setStartAfter(node);
rng.collapse(true);
sel.removeAllRanges();
sel.addRange(rng);
}
}
else if (typeof document.selection !== 'undefined' && document.selection.type !== 'Control')
{
document.selection.createRange().pasteHTML(node.outerHTML);
}
}
However though this works perfectly in IE, Opera and Firefox it doesn't work in Chrome and Safari. In Chrome/Safari the cursor is placed at the end of the text within the span, rather than after the span. ie
<span>text CURSOR HERE</span>
instead of what I am wanting, which is:
<span>text</span>CURSOR HERE
Thanks.