Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting selected text position

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.

like image 317
Ecarrion Avatar asked Mar 03 '11 04:03

Ecarrion


People also ask

What is window getSelection?

getSelection() The Window. getSelection() method returns a Selection object representing the range of text selected by the user or the current position of the caret.


2 Answers

s = window.getSelection(); 

Returns a Selection. So try

s = window.getSelection(); oRange = s.getRangeAt(0); //get the text range oRect = oRange.getBoundingClientRect(); 

oRect will be the bounding rectangle in client (fixed) coordinates.

like image 110
Jerinaw Avatar answered Sep 28 '22 02:09

Jerinaw


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?

like image 34
Tim Down Avatar answered Sep 28 '22 01:09

Tim Down