Reputation: 3670
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();
}
}
}
Upvotes: 4
Views: 1838
Reputation: 3670
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);
}
}
}
Upvotes: 6