I need the coordinates in pixels of the beginning of the text selection (anywhere on the page, not in a textarea).
I tried using the cursor coordinates but this didn't work quite well because the cursor coordinates and the beginning of the selection are not always the same (for example when a user drags over a text).
I hope someone has the solution!
In IE >= 9 and non-IE browsers (Firefox 4+, WebKit browsers released since early 2009, Opera 11, maybe earlier), you can use the
getClientRects()
method ofRange
. In IE 4 - 10, you can use theboundingLeft
andboundingTop
properties of theTextRange
that can be extracted from the selection. Here's a function that will do what you want in recent browsers.Note that there are some situations in which you may wrongly get co-ordinates
0, 0
, as mentioned in the comments by @Louis. In that case you'll have to fall back to a workaround of temporarily inserting an element and getting its position.jsFiddle: http://jsfiddle.net/NFJ9r/132/
Code:
UPDATE
I submitted a WebKit bug as a result of the comments, and it's now been fixed.
https://bugs.webkit.org/show_bug.cgi?id=65324
The above answer by TimDown does not work if the caret is in an empty element.
The code below solves the problem. Note how it is almost identical to TimDown's solution except that this code checks the
range.getClientRects()
array haslength>0
before callingrange.getClientRects()[0]