1

I am not able to find an answer to this question. One of my use cases is to show a small popup beneath the current caret position in a contenteditable. I need to find the position (the DOM position) of the caret before I can display this popup properly.

All searches I have done usually end up trying to find the text position of the caret and not the actual XY relative to the DOM. How can this be achieved?

EDIT: Component's textarea-caret-position plugin does not help as it looks like a plugin specifically for inputs and textarea's. I will need something for contenteditable.

Stalfos
  • 1,348
  • 2
  • 9
  • 12
  • Possible duplicate of [How do I get the (x, y) pixel coordinates of the caret in text boxes?](http://stackoverflow.com/questions/29709/how-do-i-get-the-x-y-pixel-coordinates-of-the-caret-in-text-boxes) – Sam Hanley Jan 25 '17 at 15:44
  • See my edit, the top answer in that link provides a plugin that doesn't seem like it'll work for my use. – Stalfos Jan 25 '17 at 15:57

1 Answers1

0

I was able to overcome this issue after some insight on Component's textarea-caret-position. All I did here was to insert a temporary node at the current caret position, and then get the coordinates of this node (which is at the position of the caret). Once the coordinates are received, remove the temporary node.

var selection = this.document.getSelection();
var node = selection.anchorNode;
var domNode = node.nodeType === 3 ? node.parentNode : node;

var tempDomNode = $("<span class='caret'></span>");
var tempNode = tempDomNode[0];

domNode.appendChild(tempNode);
var left = tempDomNode.offset().left;
var top = tempDomNode.offset().top;
domNode.removeChild(tempNode);

"left" and "top" should now contain the position of the caret.

Stalfos
  • 1,348
  • 2
  • 9
  • 12