The following function will insert a DOM node (element or node text) at the cursor position in all major desktop browsers:
function insertNodeAtCursor(node) { var sel, range, html; if (window.getSelection) { sel = window.getSelection(); if (sel.getRangeAt && sel.rangeCount) { sel.getRangeAt(0).insertNode(node); } } else if (document.selection && document.selection.createRange) { range = document.selection.createRange(); html = (node.nodeType == 3) ? node.data : node.outerHTML; range.pasteHTML(html); } }
If you prefer to embed an HTML string:
function insertHtmlAtCursor(html) { var sel, range, node; if (window.getSelection) { sel = window.getSelection(); if (sel.getRangeAt && sel.rangeCount) { range = window.getSelection().getRangeAt(0); node = range.createContextualFragment(html); range.insertNode(node); } } else if (document.selection && document.selection.createRange) { document.selection.createRange().pasteHTML(html); } }
I adapted this from my answer to a similar question: How to find the cursor position in the content DIV?
Tim down
source share