8

I would like to position element above selected text. But I am not able to figure out the coordinates.

var sel = document.getSelection();
  if(sel != null) {
    positionDiv();
}

Example: (image)

alt text

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
priyank
  • 4,634
  • 11
  • 45
  • 52

1 Answers1

4

Here is the basic idea. You insert dummy element in the beginning of the selection and get the coordinates of that dummy html element. Then you remove it.

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);
Ivo Sabev
  • 5,230
  • 1
  • 26
  • 38
  • Take a look here, it might be a better way to determine the dummy's position - http://www.quirksmode.org/js/findpos.html I usually use jQuery and the offset plugin so I don't have issues with browser compatibility. – Ivo Sabev Apr 09 '10 at 06:41
  • Can you please provide me the link for jquery plugin? thanks. – priyank Apr 09 '10 at 07:43
  • 1
    None of this will work in IE, which has a completely different mechanism for obtaining and manipulating user selections. Also, `document.getBoxObjectFor` is a Mozilla extension that is now deprecated, and was never intended for use in web pages in the first place. – Tim Down Apr 09 '10 at 09:19
  • 1
    @Tim: `document.getBoxObjectFor` is completely gone as of FF 3.6. – Crescent Fresh Apr 09 '10 at 12:58
  • The library is jquery.com here is example - http://stackoverflow.com/questions/683339/how-do-i-find-the-absolute-position-of-an-element-using-jquery – Ivo Sabev Apr 09 '10 at 13:19
  • `dummy.getBoundingClientRect()` is a suitable replacement for `document.getBoxObjectFor(dummy)` – Toastrackenigma Nov 07 '19 at 04:43