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.
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
collapsemethod of your cloned range instead of collapsing/restoring the selection.