2

I have a long text field and what I want to do is that when a user types an '@' character a list of users appear just like a typical auto-complete. However I want the list of users to appear below the '@' character which could be 20-30 characters in from the start of the text box.

I've found many jQuery auto-complete plugins but none that position the list below the current caret position.

I can get the text field position using $('#textfield').position() and I can get the caret position using something like this but that gets the character index from the text value and not the pixel position.

How can I get the current carret position of a text field relative to the page in pixels in order to position an element below it?

Community
  • 1
  • 1
David Glenn
  • 24,412
  • 19
  • 74
  • 94
  • if you can get the textfield postion which is relative to the screen and just simply add the carret position which is relative to the text box i guess. you will have the carret position relative to the screen. no?... – guy schaller Jul 15 '10 at 09:49
  • 2
    @guy The caret position in the example is the character index of the text value and not the pixel position of the caret. – David Glenn Jul 15 '10 at 10:07
  • I've edited the question to make it a bit clearer but `position()` gets the pixel position whilst the example I gave gets the character index of the caret. What I need to know is basically, how do I add them together? – David Glenn Jul 15 '10 at 10:12

3 Answers3

2

relaying on this anwsear: Calculate text width with JavaScript

what you can do is have a div on the screen which is visible:hidden then every time a new charecter has been entered to the textbox change the inner html of the div

so the textbox value and the div innerhtml will always be synced.

then when you want to popup your autocomplete you will add the width of the div. to the offset left postion of the textbox.

and thats it...

and avcorse you will need that the div and the textbox will have the same font...

Community
  • 1
  • 1
guy schaller
  • 4,710
  • 4
  • 32
  • 54
1

This jQuery plugin does what you're after:

http://plugins.jquery.com/project/caretPosition

I haven't tested it, but going by the code it looks like it creates a temporary <span> with the same content as your <textarea> (up to the cursor) and makes wild assumptions about font, line height, whitespace and word wrapping when measuring it.

You could try extending it to:

  1. Copy the font, line height, whitespace and word wrap styles from the target <textarea>

  2. Hide the temporary <span> without affecting the measurement by wrapping it in a <div style="height: 0; overflow: hidden;"> or positioning it absolute -9999px, -9999px

Richard Poole
  • 3,946
  • 23
  • 29
-2
$(this).position().top ;
$(this).position().left ;
$(this).position().right ; etc... :-)