Mar 8, 2010

Calculating the cursor position in textarea with JavaScript

I've been spending some time writing tag support in Checkvist, and decided to share a bit of related JavaScript code.

The idea is to allow adding tags with smart syntax: when you write "Call Bob regarding new furniture tomorrow #home" Checkvist will create a task "Call Bob regarding new furniture" with due tomorrow and with tag #home.

The additional nicety could be the tag completion after the '#' character. But here comes a problem - how to show the completion popup near the cursor position in the textarea? The typical approach used in or GMail is to show the popup under the text field, but it doesn't look good when your cursor is far from the popup, in the beginning of a large text area.

After some googling I didn't find an existing solution. The only helpful code was detection of the text cursor position relatively to the beginning of the string.

To convert this position into pixel coordinates, one has to find out how the text is organized within the textarea, where linebreaks are, how many lines are there in the text, and so on. This, in turn, depends on the font metrics of the text and requires answer for the question "What is the length of the given string if it is placed into this textarea?".

The answer for the last question can be obtained if you create a div with the same font metrics as the original textfield, give it absolute positioning, put a string into it, and take its width. Using such a function, you can model text wrapping in the textarea, and find out the actual X,Y coordinates of the cursor in the textarea.

You can find my implementation of this approach on GitHub (BTW, a really great place to share open-source code). This library was tested with FF3, Chrome, IE, Opera, Safari. There may be some glitches, but they are rare and I'm pretty comfortable with the results so far. There is no need for Prototype, jQuery or other Javascript libraries to use the code.

I hope this code will be useful to someone else, and if so, please drop me a line :)

5 comments: said...

very cool & good tip, thank you very much for sharing.

Can I share this post on my JavaScript library?

Awaiting your response. Thank

Unknown said...

Surely, if you find it useful :)

Anonymous said...

just as much of a pain as I expected. Thank you for writing it first.

Nicholas Riley said...

I tried the test page with current versions of Safari, Chrome and Firefox and none of them moved the red dot much out of the top left corner of the box... did something break since you posted it?

I've got (10-year-old) code for IE that I'm porting, which works fine since IE unifies the selection model for textareas and other DOM elements.

Unknown said...

Ups, looks like my final change in the test file broke the test. I've fixed the problem now, thanks for pointing out!