views:

157

answers:

1

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

+2  A: 

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
Thanks a ton...
priyank
You are more than welcome.
Ivo Sabev
Does getBoxObjectFor work for IE?
priyank
Take a look here, it might be a better way to determine the dummy's position - http://www.quirksmode.org/js/findpos.htmlI usually use jQuery and the offset plugin so I don't have issues with browser compatibility.
Ivo Sabev
Can you please provide me the link for jquery plugin? thanks.
priyank
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
@Tim: `document.getBoxObjectFor` is completely gone as of FF 3.6.
Crescent Fresh
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