I have a contenteditable div where I need to insert text at the caret position,
This can be easily done in IE by document.selection.createRange().text = "banana"
Is there a similar way of implementing this in Firefox/Chrome?
(I know a solution exists here , but it can't be used in contenteditable div, and looks clumsy)
Thank you!
just an easier method with jquery:
copy the entire content of the div
var oldhtml=$('#elementID').html();
var tobejoined='<span>hii</span>';
//element with new html would be
$('#elementID').html(oldhtml+tobejoined);
simple!
The following function will insert text at the caret position and delete the existing selection. It works in all the mainstream desktop browsers:
UPDATE
Based on comment, here's some code for saving and restoring the selection. Before displaying your context menu, you should store the return value of
saveSelection
in a variable and then pass that variable intorestoreSelection
to restore the selection after hiding the context menu and before inserting text.window.getSelection()
.Selection.getRangeAt(0).insertNode()
to add a textnode.If necessary, move the cursor position behind the added text with
Selection.modify()
. (Not standardized, but this feature is supported in Firefox, Chrome and Safari)