4

I'm looking to get the X/Y coordinates of the caret within a textarea on key down. I've searched vigorously but without any luck whatsoever, it seems you can get the position, but not the on-screen X/Y coordinates.

0

2 Answers 2

5

The only viable way of doing this, AFAIK:

  1. Append the contents of the TEXTAREA to a DIV
  2. Append the DIV to the DOM
  3. Place a SPAN inside the DIV at the character offset of the caret.
  4. Take the offset of the SPAN ($(span).offset()...) and minus the offset of the DIV (depending on whether you want the x/y coords relative to the textarea or the page)

Note: When copying the text from the TEXTAREA to the DIV, make sure to copy relevant CSS properties that may affect the offset (width, height, padding, margin, border, font-size, line-height etc.).

1
2

I wrote this jQuery plugin for exactly that.

3

Not the answer you're looking for? Browse other questions tagged or ask your own question.