Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the coordinates of the end of selected text with javascript?

My problem is similar to this, but I need a way to get the coordinates of the right side of the selection with Javascript in Firefox. I made a small example to show what I mean:

alt text

The code I got from the other post is the following:

var range = window.getSelection().getRangeAt(0);
var dummy = document.createElement("span");
range.insertNode(dummy);
var box = document.getBoxObjectFor(dummy);
var x = box.x, y = box.y;
dummy.parentNode.removeChild(dummy);

This gives me the coordinates of the beginning of the selection. Is there any way to retrieve the coordinates of the end of the selection?

like image 427
Bob Avatar asked Sep 22 '10 08:09

Bob


1 Answers

Yes. That bit's quite simple: you just need to call collapse(false) on the Range obtained from the selection. Be aware that document.getBoxObjectFor() has now been removed from Mozilla, so you need the dummy element's getBoundingClientRect() method instead:

var range = window.getSelection().getRangeAt(0);
range.collapse(false);
var dummy = document.createElement("span");
range.insertNode(dummy);
var rect = dummy.getBoundingClientRect();
var x = rect.left, y = rect.top;
dummy.parentNode.removeChild(dummy);
like image 81
Tim Down Avatar answered Oct 27 '22 22:10

Tim Down