Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Position cursor after element when inserting into contenteditable?

I want to be able to insert images, wrapped in a span, into a contenteditable div. I can do this no problem but then when I go to type, after the image, it inserts my text into the images span. How do I position the cursor AFTER the span that I just inserted?

Here is my fiddle (click "Add Image at Cursor" and the enter text into the content editable. Observe the text is inside the images parent span.)

Here is my image insert function:

function insertElementAtCursor(elm) {
    var sel, range, html;
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.getRangeAt && sel.rangeCount) {
            range = sel.getRangeAt(0);
            range.deleteContents();
            range.insertNode(elm);
            placeCaretAfterNode(elm);
            updateTextArea();
        }
    }
}
like image 393
user1873073 Avatar asked Oct 25 '25 15:10

user1873073


1 Answers

Added a text node after the span and moved the range to that

function insertElementAtCursor(elm) {
    var sel, range, html;
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.getRangeAt && sel.rangeCount) {
            range = sel.getRangeAt(0);
            range.deleteContents();
            range.insertNode(elm);

            var textNode = document.createTextNode('\u00A0');
            range.setStartAfter(elm);
            range.insertNode(textNode);
            range.setStartAfter(textNode);
            range.collapse(true);
            sel = window.getSelection();
            sel.removeAllRanges();
            sel.addRange(range);
        }
    }
}
like image 193
user1873073 Avatar answered Oct 28 '25 01:10

user1873073