Currently I'm getting the selected text in the browser doing this:
window.getSelection();
Now I need to show a tooltip above that text when pressing a custom key(note that the mouse could not be over the text anymore), so in order to do that I need the absolute position of that selected text.
Is there a way to do that, maybe wrapping that text inside a tag and then getting the offsets? It just has to work in Chrome, not all browsers.
Before using
getBoundingClientRect
, you need to know this note:And by this 'standard':
So if anyone reading this post wants a general solution for more precise positions and layouts of selected texts, I suggest the following approaches:
Option 1: Find exact starting and and ending point of texts by inserting invisible elements. Then calculate selected line rectangles with extracted computed line height and container width. APIs in use: window.getComputedStyle.
Option 2: Wrap each text with a carefully styled inline element, extracting layout of each box, and merge results into lines.
For option 2, rangeblock is an existing implementation with an easy API which gives you the absolution layout of each line of text:
The easiest way is to insert a temporary marker element at the start or end of the selection and get its position. I've demonstrated how to do this before on Stack Overflow: How can I position an element next to user text selection?
Returns a Selection. So try
oRect will be the bounding rectangle in client (fixed) coordinates.