I want to insert some html in a contenteditable div.
When editing the content, the user clicks on an icon, a dialog pops and he enters the url & anchor text in the dialog. This causes that the editable div loses its focus and the link is inserted at the beginning of the div, not when the caret was. I tried many things but I’m stuck.
“rte” id of my editable content div
“link_add” id of button in dialog
$('#link_add').click(function (e)
{
$('#rte').focus();
document.execCommand('insertHTML', false, 'html content test');
close_modal ();
e.preventDefault();
});
I also tried the solution from set execcommand just for a div, using:
function execCommandOnElement(el, commandName, value)
But this empties the div and just paste the new content.
I take it this is an “inline” dialog (much like StackOverflow’s link dialog, for instance), which moves the focus and therefore the selection. The solution seems to be to save and restore the selection. Call getSelection() to get a reference to the selection and save the
anchorNode,anchorOffset,focusNodeandfocusOffsetproperties and then usecollapse(anchorNode, anchorOffset)andextend(focusNode, focusOffset)to restore the selection once you have focused the contenteditable div. (If you’re not interested in both nodes you could justcollapse(focusNode, focusOffset).)