I use this code How can I position an element next to user text selection? to get the position of the selected text, but it doesn\'t work for the selected text inside an input.
The question is about getting the position of mouse pointer when selecting text. I am trying a solution that also works with keyboard events (choosed keyup
).
I wrote a sample html page with a "vanilla" script inside to test the capabilities of the Selection API. This is the idea:
When selecting on text nodes, getting the position of selected text is done by means of the Range Object.
But when the selected text is a part of an Input Element
, using the getBoundingClientRect()
of the Range Object does not work (gave me a full zero ClientRect Object
.
So, the function getSel() will try to consider both scenarios: selecting text just from the HTML or inside some input elements (just considered input
and textarea
).
On the bottom of the page there is a div#results
element, for displaying data, then getSel()
will create a new div#boundy with the coordinates of the ClientRect object or the related input element coordinates.
I wish to finish it, but I'm out of ideas on how to get the actual position of the selected text inside the input objects. It will have to be adding in a relative way to the coordinates of the element itself.
Answering Andrew, if this works, you'll be able to use the coordinates of div#boundy to place the tooltip wherever you want.
I've created a codepen here.