2

I am using range.getBoundingClientRect to get caret position but it gives wrong values when the end key is pressed.

Currently, I have a content-editable div and a caret div:

<div id="editor" contenteditable="true">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce sodales tellus nulla, quis viverra ipsum accumsan nec. Vivamus felis velit, dictum nec purus sed, placerat placerat libero. 
</div>
<div id="caret"></div>

I detect when selection change to update caret position:

document.addEventListener("selectionchange", function() {
  const rect = document.getSelection().getRangeAt(0).getBoundingClientRect();
  document.getElementById('caret').style.left = `${rect.left}px`;
  document.getElementById('caret').style.top = `${rect.top}px`;
})

When I press the end key, my caret goes at the beginning of the next line instead of going at the end of the current one. This is because getBoundingClientRect gives bad values.

Here is a reproduction:

https://jsfiddle.net/2dauymov/10/

I am on Chrome 78.

Lucas Willems
  • 6,673
  • 4
  • 28
  • 45

0 Answers0