4

I can use document.createRange() to get a range of individual characters in a textnode, then Range.getBoundingClientRect() to get the position on the screen of those characters. I want to do the same thing for text in an input element, which used to be possible in IE only with createTextRange.

This jsfiddle sums up the problem - http://jsfiddle.net/sobu5ug2/2/

I can't use the same method for an input because Range.setStart/End only works on the element level, not the character level, for an input. I also tried window.getSelection().getRangeAt(0).getBoundingClientRect() but that returns a bounding rect of all 0's. I'd like to do this without actually selecting the text, if possible.

Is there any way to do this in a modern browser? Thanks.

Rob Lourens
  • 15,081
  • 5
  • 76
  • 91

1 Answers1

0

Here is an example how to do it:

https://jh3y.medium.com/how-to-where-s-the-caret-getting-the-xy-position-of-the-caret-a24ba372990a

You need to create a div, copy all styles of the input element into that div, copy text up to the selection into that div, add a span inside that div with the selection and then you can measure this span relative to the div before removing the div again.

Christian
  • 2,903
  • 4
  • 31
  • 34