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();
}
}
}
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);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With