Reputation: 2028
I think this question is simple, but I've been unable to figure it out. I hit a stopping point using the simpler solution for getting the caret position in a contenteditable div from Get caret position in contentEditable div. I've been attempting to get the line number of the caret position, and I've got a lot of the logic done, but because that one treats the end of one line the same as it treats the start of the next, it's proven pretty much impossible.
So, instead I've been trying to use the rangy library to get the caret position, in the hope that it treats the end of lines appropriately(counting the end of a line as one less than the start of the next,) but I haven't quite figured out how to get it to work the way I'd like. My code looks like this:
var sel = rangy.getSelection();
var range = sel.getRangeAt(0);
var cursorPos = sel.focusOffset;
It seems to work when I hit enter to go to a new line (the position is incremented by 1) but after that the caretPos starts again at 0 at the start of each line. Is there a way to get an overall cursor position, which accounts for new lines? To be clear, I'm not asking how to get the line number from rangy, just the caret position.
Thank you, and sorry if I'm missing something obvious.
Upvotes: 2
Views: 986
Reputation: 151441
Rangy by itself does not have the capability to give you line numbers. sel.focusOffset
in the code you show in the question is either an offset among the children of an element node or an offset in the text of a text node. If it appears to you to correspond to a line number, this is just chance.
Basically, rangy would not play an essential role in the problem you are presenting. Whatever system that would be able to provide line numbers would be able to work independently of rangy.
Edit in response to comment: Your question says "in the hope that it treats the end of lines appropriately(counting the end of a line as one less than the start of the next,)". Since the topic of conversation is Rangy, I'm understanding "it" as "Rangy." Rangy does not have a notion of "end of line", so it cannot treat them in any fashion.
Upvotes: 1