Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Getting caret line number. #278

Open
UhMarco opened this issue Feb 13, 2023 · 0 comments
Open

Getting caret line number. #278

UhMarco opened this issue Feb 13, 2023 · 0 comments

Comments

@UhMarco
Copy link

UhMarco commented Feb 13, 2023

We're able to get the index of the caret by doing something like this:

function getCaretPosition(element: HTMLElement) {
  var sel = window.getSelection()!;
  if (!sel.rangeCount) return -1;

  var range = sel.getRangeAt(0);
  var preCaretRange = range.cloneRange();
  preCaretRange.selectNodeContents(element);
  preCaretRange.setEnd(range.endContainer, range.endOffset);
  var caretPosition = preCaretRange.toString().length;
  return caretPosition;
}

Is it possible to get the line number? I've tried splitting the innerHTML of the div by "<br>" and finding the length of the first string. If the string has length, I can see if the caret position is greater than or equal to the length and if this is true, the caret is either at the end of the first line or below. However, if the first line is empty and the innerHTML consist of only new lines, I haven't been able to find a way of working out the caret line number.

Does anyone know of a solution to find out the caret line number no matter the content of the div?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant