<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 button, 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;
}
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.