Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the pixel offset from the current caret position in an iframe with contentEditable

I would like to position a floating div element in an iframe with contentEditable, in case the user enters a certain key combination (for auto-complete purposes).

I know how to get the caret position: document.getElementById('elm1_ifr').contentWindow.getSelection().anchorOffset

I can use this to calculate the left property of the div, but I can't seem to figure out how to get the top.

Another possibility I thought about was using: document.getElementById('elm1_ifr').contentWindow.getSelection().anchorNode.parentNode

And using jQuery to get the offset, but if that parent has a long text line, I would only be able to extract the top position of the first line.

Can anyone help me with this?

like image 343
Mor Shemesh Avatar asked Dec 10 '11 12:12

Mor Shemesh


1 Answers

The only reliable way of doing this is to insert a temporary element at the caret (ensuring that it is zero width), get its position and remove it again. You should also glue the two ends of the text node (if it was a text node that contained the caret) back together to ensure the DOM is as it was before inserting the node. Note, however, that doing this (or any other manual DOM manipulation on the editable content) breaks the browser's internal undo stack.

The reason for this is that careful reading of the spec for the getBoundingClientRect() method of Range shows that getBoundingClientRect() is not obliged to return a Rect for a collapsed Range. Conceptually, not every position in the document has a well-defined bounding rectangle. The caret, however, does have physical location on the screen which in my opinion should be provided by the Selection API, but currently there is nothing in browsers to provide this.

like image 192
Tim Down Avatar answered Sep 28 '22 03:09

Tim Down