JSFiddle - React, Tailwind, and code Playground
HTML
<a href="http://stackoverflow.com/questions/5478891/how-can-i-get-the-caret-position-on-a-contenteditable-button/5479734#5479734">Fiddle for http://stackoverflow.com/questions/5478891/how-can-i-get-the-caret-position-on-a-contenteditable-button/5479734#5479734</a>
<br/>
Uses code from <a href="https://niichavo.wordpress.com/2009/01/06/contenteditable-div-cursor-position/">https://niichavo.wordpress.com/2009/01/06/contenteditable-div-cursor-position/</a>
<br/>
<hr/>
<button id="test" contentEditable="true">This <img src="image.png" /> is a <b>button</b>, click me!</button>
<br/>
Cursor Position: <span id="pos">-</span>
JavaScript
$('#test').keyup(function(){
$('#pos').text(getCursorPos());
});
function getCursorPos() {
var cursorPos;
if (window.getSelection) {
var selObj = window.getSelection();
var selRange = selObj.getRangeAt(0);
cursorPos = findNode(selObj.anchorNode.parentNode.childNodes, selObj.anchorNode) + selObj.anchorOffset;
/* FIXME the following works wrong in Opera when the document is longer than 32767 chars */
return cursorPos;
}
else if (document.selection) {
var range = document.selection.createRange();
var bookmark = range.getBookmark();
/* FIXME the following works wrong when the document is longer than 65535 chars */
cursorPos = bookmark.charCodeAt(2) - 11; /* Undocumented function [3] */
return cursorPos;
}
}
function findNode(list, node) {
for (var i = 0; i < list.length; i++) {
if (list[i] == node) {
return i;
}
}
return -1;
}