There is a jquery plugin.caret (http://plugins.jquery.com/caret/) which allows a simple call tovar position = $("#myeditable").caret();
to get the cursor position inside the editable div. The plugin is small, ~60 lines, and it is easy to understand.
However, it defines the position relative to the text.
If you need to check, for example, that the cursor was in specified span, clumsy way to get around the text nodes until their total length will not be more than the position of the cursor.
This can be done using the createTreeWalker
getTextNodeByCaret function(caret) {
var len = 0;
var walk = document.createTreeWalker($("#myeditable")[0], NodeFilter.SHOW_TEXT, null, false);
var last;
var node;
while ((node = walk.nextNode())) {
last = node;
if ((len += node.textContent.length) >= caret) {
return node;
}
}
return last;
}
Find more questions by tags HTMLJavaScript