Selection expands in any direction

137 Views Asked by At

I'm trying to animate scrolling behaviour in a TinyMCE contenteditable. For this, i try to get the actual position of the cursor/caret. One way for getting the 'end'-cursor would be:

function getPositionFromSelection (selection, position = 'end') {
  const prevRange = selection.getRangeAt(0).cloneRange()
  if (position === 'start') { selection.collapseToStart() } else { selection.collapseToEnd() }
  const caret = selection.getRangeAt(0).getBoundingClientRect()
  selection.removeAllRanges()
  selection.addRange(prevRange)
  return caret.top
}

When i get the position like this it seems okay until i try to shrink the selection. The caret jumps to the other end of the selection and expands it.

MWE: https://codepen.io/hydrair/pen/PoePOoq

1

There are 1 best solutions below

0
Pixievolt No. 1 On

I can't reproduce the behavior you describe in Chrome or Firefox, but I can tell you it's not necessary to modify the selection as your code is doing. Use the collapse method of your cloned range instead of collapsing/restoring the selection.