Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Editable Div Caret Position

I have an editable div and I am using a button to insert an image into the div. Right now, I am just doing document.getElementById('elementid').innerHTML. += ; in order to get the image added to the end of the div. I would like to enter the image where the caret is. How would I go about doing this?

Thanks

like image 473
intl Avatar asked Oct 14 '22 20:10

intl


2 Answers

To insert an element at the caret is not too hard. The following function inserts a node at the caret (or at the end of the selection, if content is selected) in all major browsers:

function insertNodeAfterSelection(node) {
    var sel, range, html;
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.getRangeAt && sel.rangeCount) {
            range = sel.getRangeAt(0);
            range.collapse(false);
            range.insertNode(node);
        }
    } else if (document.selection && document.selection.createRange) {
        range = document.selection.createRange();
        range.collapse(false);
        html = (node.nodeType == 3) ? node.data : node.outerHTML;
        range.pasteHTML(html);
    }
}
like image 93
Tim Down Avatar answered Oct 30 '22 21:10

Tim Down


I hate to sound negative, but this is so hard it's ridiculous. You have to deal with IE and others, and the implementations are vastly different. But where it gets uber-hard is that if you click a button to insert the image, you lose focus and the caret position, so you need to remember the position with some onblur bookmarking ability (again, IE different). The focus thing is not so much an issue if your editablecontent is in an iframe and maintains its own focus. (Note: not dissing IE here, I actually prefer their implementation to the W3C standard drek.)

You can look at some open source text editors for clues and hints. But you'll find an enormous amount of code to handle these simple tasks.

like image 28
mwilcox Avatar answered Oct 30 '22 23:10

mwilcox