Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Contenteditable text editor and cursor position

How can I (using jquery or other) insert html at the cursor/caret position of my contenteditable div:

<div contenteditable="true">Hello world</div>

For example, if the cursor/caret was between "hello" and "world" and the user then clicked a button, eg "insert image", then using javascript, something like <img src=etc etc> would be inserted between "hello" and "world". I hope I've made this clear =S

Example code would be greatly appreciated, thanks a lot!

like image 926
N S Avatar asked May 30 '10 08:05

N S


1 Answers

The following function will insert a DOM node (element or text node) at the cursor position in all the mainstream 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 would rather insert 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've adapted this from my answer to a similar question: How to find cursor position in a contenteditable DIV?

like image 95
Tim Down Avatar answered Sep 23 '22 23:09

Tim Down