Skip to content

Instantly share code, notes, and snippets.

@jrainlau
Created September 7, 2018 05:39
Show Gist options
  • Save jrainlau/99fa329f0a4b5d891aa09de7f63b1814 to your computer and use it in GitHub Desktop.
Save jrainlau/99fa329f0a4b5d891aa09de7f63b1814 to your computer and use it in GitHub Desktop.
get and set cursor position
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