3

I want to position a pop-up element directly below the text caret/blinking text cursor in a textarea or content editable element.

I've found answers that give me the text index within an element where the caret exists, but as far as I can tell this is useless to me. (like this)

I need something similar to the event.pageX and pageY properties available with mouse-events, but I want that same thing for the position of my text editor caret. Anyone know how to do this?

Ethan
  • 748
  • 1
  • 8
  • 26

1 Answers1

1

You can't get the exact coordinates of the text caret effortlessly, but this snippet will give you a rect object with the approximate coordinates of the window's current selection. You may have to also add/subtract use additional offsets of containing elements depending on your styling.

const selection = window.getSelection();
const range = selection.getRangeAt(0);
rect = range.getBoundingClientRect();
Slbox
  • 7,771
  • 10
  • 42
  • 90
  • 1
    Wow, actually this looks like it's exactly what I was after. I am now embarrassed about the direction I was going trying to get this same type of output. I think there might be some stuff I have to adjust/account for as you mention but this is great! – Ethan Sep 06 '20 at 23:56
  • This doesn't work anymore all the values in the rect return 0 for me. – Tenpi Apr 28 '22 at 14:35
  • No, it works still - we still use this code in Chrome 98. It may not work in your particular environment though. – Slbox Apr 28 '22 at 18:24