Skip to content

Instantly share code, notes, and snippets.

@tranghaviet
Created July 11, 2019 04:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tranghaviet/16c54f010e1900d55a61600d017ba828 to your computer and use it in GitHub Desktop.
Save tranghaviet/16c54f010e1900d55a61600d017ba828 to your computer and use it in GitHub Desktop.
place caret at end of contenteditable element
function placeCaretAtEnd(el) {
el.focus()
if (typeof window.getSelection != "undefined"
&& typeof document.createRange != "undefined") {
const range = document.createRange()
range.selectNodeContents(el)
range.collapse(false)
const sel = window.getSelection()
sel.removeAllRanges()
sel.addRange(range)
} else if (typeof document.body.createTextRange != "undefined") {
const textRange = document.body.createTextRange()
textRange.moveToElementText(el)
textRange.collapse(false)
textRange.select()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment