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!
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
saveSelectionin a variable and then pass that variable intorestoreSelectionto restore the selection after hiding the context menu and before inserting text.