To determine the location of the text cursor in an editable div?

Trying to determine where the courses in the div editable, searched Google from top to bottom, found a working solution, but the text
ab
with the cursor between the letters "a" and "b" I it is reported that the cursor on the first symbol, i.e., html tags are ignored, and I need to, and they were taken into account.

Very hope for your help.
October 3rd 19 at 02:09
1 answer
October 3rd 19 at 02:11

There is a jquery plugin.caret (http://plugins.jquery.com/caret/) which allows a simple call to
var 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