I have this contenteditable div
<div contenteditable="true" id="text">minubyv<img src="images/smiley/Emoji Smiley-01.png" class="emojiText" />iubyvt</div>
Here is a description of the code output image 
so I want to get the position of the carriage div and suppose the cursor is after the last character. And this is my code to get the caret position
function getCaretPosition(editableDiv) { var caretPos = 0, sel, range; if (window.getSelection) { sel = window.getSelection(); if (sel.rangeCount) { range = sel.getRangeAt(0); if (range.commonAncestorContainer.parentNode == editableDiv) { caretPos = range.endOffset; } } } else if (document.selection && document.selection.createRange) { range = document.selection.createRange(); if (range.parentElement() == editableDiv) { var tempEl = document.createElement("span"); editableDiv.insertBefore(tempEl, editableDiv.firstChild); var tempRange = range.duplicate(); tempRange.moveToElementText(tempEl); tempRange.setEndPoint("EndToEnd", range); caretPos = tempRange.text.length; } } return caretPos; } var update = function() { console.log(getCaretPosition(this)); }; $('#text').on("mousedown mouseup keydown keyup", update);
But the problem is that it returns 6
instead of 14
. The carriage position returns to 0
after the image. Please there is a way that I can get the position of the carriage 14
in this case.
EDIT
I also want to insert an element starting at the caret position. so this is my function to do it
selectStart = 0; var update = function() { selectStart = getCaretPosition(this); }; function insertEmoji(svg){ input = $('div#text').html(); beforeCursor = input.substring(0, selectStart); afterCursor = input.substring(selectStart, input.length); emoji = '<img src="images/smiley/'+svg+'.png" class="emojiText" />'; $('div#text').html(beforeCursor+emoji+afterCursor); }
source share