Skip to content

Instantly share code, notes, and snippets.

@nmanikiran
Created March 11, 2020 07:32
Show Gist options
  • Save nmanikiran/5722aabc5bc6baf860f2b29876baa820 to your computer and use it in GitHub Desktop.
Save nmanikiran/5722aabc5bc6baf860f2b29876baa820 to your computer and use it in GitHub Desktop.
getCursorPosition from contenteditable
getCursorPosition(editableDiv) {
editableDiv = editableDiv || this.element;
let caretOffset = 0;
if (window.getSelection) {
const range = window.getSelection().getRangeAt(0);
const preCaretRange = range.cloneRange();
preCaretRange.selectNodeContents(editableDiv);
preCaretRange.setEnd(range.endContainer, range.endOffset);
caretOffset = preCaretRange.toString().length;
} else if (document.selection && document.selection.type !== 'Control') {
const textRange = document.selection.createRange();
const preCaretTextRange = document.body.createTextRange();
preCaretTextRange.moveToElementText(editableDiv);
preCaretTextRange.setEndPoint('EndToEnd', textRange);
caretOffset = preCaretTextRange.text.length;
}
return caretOffset;
},
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment