7

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?

Community
  • 1
  • 1
Bob
  • 999
  • 1
  • 9
  • 12

2 Answers2

10

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);
Tim Down
  • 318,141
  • 75
  • 454
  • 536
  • +1 for being 3 seconds faster. I didn't know *getBoxObjectFor()* had already been removed. – Andy E Sep 22 '10 at 08:53
  • 1
    I remembered that because a few months ago MooTools broke because it was detecting Mozilla using a sniff for `getBoxObjectFor()` (a method that it never used, as far as I know). – Tim Down Sep 22 '10 at 08:56
  • collapse(false) is exactly what I was searching for. Thank you so much. You helped me a lot. – Bob Sep 22 '10 at 11:46
0
var r = range.cloneRange();
r.collapse(false); // collapses range clone to end of original range
r.insertNode(dummy);
// document.getBoxObjectFor(dummy), etc.
Alex Gyoshev
  • 11,929
  • 4
  • 44
  • 74