Created
September 7, 2018 05:39
-
-
Save jrainlau/99fa329f0a4b5d891aa09de7f63b1814 to your computer and use it in GitHub Desktop.
get and set cursor position
This file contains hidden or 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
export const getCursorPosition = (element) => { | |
let caretOffset = 0 | |
const doc = element.ownerDocument || element.document | |
const win = doc.defaultView || doc.parentWindow | |
const sel = win.getSelection() | |
if (sel.rangeCount > 0) { | |
const range = win.getSelection().getRangeAt(0) | |
const preCaretRange = range.cloneRange() | |
preCaretRange.selectNodeContents(element) | |
preCaretRange.setEnd(range.endContainer, range.endOffset) | |
caretOffset = preCaretRange.toString().length | |
} | |
return caretOffset | |
} | |
export const setCursorPosition = (element, cursorPosition) => { | |
const range = document.createRange() | |
range.setStart(element.firstChild, cursorPosition) | |
range.setEnd(element.firstChild, cursorPosition) | |
const sel = window.getSelection() | |
sel.removeAllRanges() | |
sel.addRange(range) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment