I don't know if the title is right. The thing is that I have found a snippet to get the cursor position when it's focused in a contenteditable element. I understand the whole code, but there are five lines that I do no t know for what they are good.
Ok. This lines are a function, which is passed to a Treewalker as a parameter. And they deal with comparing boundary points, but, how, and for what?. I have been researching lot of days, and haven't found ists functionality yet.
function(node) {
var nodeRange = document.createRange();
nodeRange.selectNode(node);
return nodeRange.compareBoundaryPoints(Range.END_TO_END, range) < 1 ?
NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT;
}
The whole snippet is this (just to situate it in context):
function getCharacterOffsetWithin(range, node) {
var treeWalker = document.createTreeWalker(
node,
NodeFilter.SHOW_TEXT,
function(node) {
var nodeRange = document.createRange();
nodeRange.selectNode(node);
return nodeRange.compareBoundaryPoints(Range.END_TO_END, range) < 1 ?
NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT;
},
false
);
var charCount = 0;
while (treeWalker.nextNode()) {
charCount += treeWalker.currentNode.length;
}
if (range.startContainer.nodeType == 3) {
charCount += range.startOffset;
}
return charCount;
}
document.body.addEventListener("keyup", function() {
var el = document.getElementById("test");
var range = window.getSelection().getRangeAt(0);
document.getElementById("position").innerHTML = "Caret char pos: " + getCharacterOffsetWithin(range, el);
}, false);
It can be seen on work here: JS Fiddle
Thank you a lot, I just want to understand this stuff before working with it. Sorry for the long Post.