getSelection().collapseToEnd() does not work

34 Views Asked by At

What I am trying to do is move the caret to the end of the string when the element is focused.

collapseToEnd() does not work. Instead, if you uncomment getSelection().collapseToEnd(), it seems to remove the selection altogether or favors the user selection.

Any help would be greatly appreciated.

const div = document.querySelector('div')

div.addEventListener('focus', moveCaretToEnd)

function moveCaretToEnd() {
  getSelection().setBaseAndExtent(
    div.childNodes[0], div.textContent.length,
    div.childNodes[0], div.textContent.length-1
  )
  // getSelection().collapseToEnd()
  // getSelection().collapse(div.childNodes[0], div.textContent.length) // also does not work
}
div {
  width: 500px;
  height: 150px;
  font-size:  3rem;
  background: skyblue;
}
<div contenteditable>This is a test</div>

0

There are 0 best solutions below