Created
March 11, 2020 07:32
-
-
Save nmanikiran/5722aabc5bc6baf860f2b29876baa820 to your computer and use it in GitHub Desktop.
getCursorPosition from contenteditable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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