Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I get co-ordinates of selected text in an html using javascript document.getSelecttion()

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

like image 293
priyank Avatar asked Apr 09 '10 04:04

priyank


1 Answers

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);
like image 141
Ivo Sabev Avatar answered Oct 13 '22 23:10

Ivo Sabev