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.
This looks like my code, from this question. It’s overly complicated for the task it’s trying to accomplish and I provided a simpler alternative to a similar question that I would recommend using instead. I’ve now updated the original answer with a link to the simpler answer.
As to your question about what that function does, it’s there to filter nodes. The TreeWalker visits all text nodes within the container node and yields only nodes those that are located before the end of the selection. The filter function is called on each text node, creates a range encompassing the text node and checks whether the end of the text node is earlier in the document than the end of the selection range using
compareBoundaryPoints().