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.

Dan Dascalescu
  • 143,271
  • 52
  • 317
  • 404
Kieran Senior
  • 17,960
  • 26
  • 94
  • 138

2 Answers2

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.).

Community
  • 1
  • 1
James
  • 109,676
  • 31
  • 162
  • 175
  • That's the general algorithm, but there are various nuances when it comes to [browser compatibility](https://github.com/component/textarea-caret-position/issues/10#issuecomment-37786158). The **Component.io** team has put together a simple [plugin that works around all edge cases, and doesn't require jQuery](http://stackoverflow.com/a/22446703/1269037). – Dan Dascalescu Mar 17 '14 at 12:11
2

I wrote this jQuery plugin for exactly that.

Amjad Masad
  • 4,035
  • 1
  • 21
  • 20
  • Great work. Simple to use. Cannot complain about it :) – ˈvɔlə Nov 07 '13 at 15:06
  • @WoIIe: I have a small complaint: if there's a scrollbar, the position may be off by one line. Also, the [caret position can be determined more simply, and without needing jQuery](http://stackoverflow.com/a/22446703/1269037). – Dan Dascalescu Mar 17 '14 at 12:09
  • Hi, next problem is with auto wrapped long text. – vašátko Oct 27 '20 at 17:54