4

I am looking for a way to get the caret x y coordinates inside a contenteditable div, in a similar manner to how you can get the mouse coordinates using window.event since I need to open a pop-up exactly where the user is with the caret inside the contenteditable div. How can I do this? Many thanks!

Crista23
  • 3,203
  • 9
  • 47
  • 60

1 Answers1

9

Here's one approach:

Coordinates of selected text in browser page

However, in some circumstances this will not give you coordinates, in which case you'd need to fall back to inserting an element at the caret, getting its position and removing the element again.

Community
  • 1
  • 1
Tim Down
  • 318,141
  • 75
  • 454
  • 536
  • Thnaks, Tim! This is exactly what I was looking for! I tested it and it returns the xy coordinates as expected on IE8, Firefox and Chrome, it's only that in Opera v 12.14 var rect = range.getClientRects()[0]; returns undefined and in IE9 for x = range.boundingLeft; y = range.boundingTop; I get x = 0 and y= 0. I need it to works on these browsers too, any tricks on how to do that? :) – Crista23 May 01 '13 at 14:18
  • Thank, Tim! I found the way to make it work on IE9 too, just as you suggested me by inserting an element at the caret and get its position. Many thanks for your much needed help and support! – Crista23 May 09 '13 at 10:09
  • I'm trying to do the same thing, it doesn't seem to work when calculating the coordinates if the caret is at the beginning of a line. May I know how have you resolved the issue? How have you inserted an element at the caret? – Rafael May 21 '14 at 11:12
  • 4
    @RafaelDiaz: Something along the lines of `var span = document.createElement("span"); span.appendChild( document.createTextNode("\u200b") /* Zero-width space character */); window.getSelection().getRangeAt(0).insertNode(span);` – Tim Down May 22 '14 at 09:02
  • @TimDown Thanks! I missed the zero-width space char, not sure why it needs to be added? And also I think the new created elements needs to be given an id, in order to delete it after use. – Rafael May 22 '14 at 09:31
  • 4
    @RafaelDiaz: The zero-width space character ensures that the element isn't considered completely collapsed by the browser, thereby ensuring that it has bounding rectangles. I can't remember if that is how it should according to the spec, I'm afraid. As for IDs, you don't need an ID if you keep a reference to the span. After the code in my previous comment, you could simply do `span.parentNode.removeChild(span)` to remove it again. – Tim Down May 22 '14 at 15:50