2

I am trying to build a username autocomplete feature in my webapp so when you type the @ symbol a little popup with an arrow appears point at your @ sign and it filters down as you continue to type the username (and clicking finishes it off).

I can do most of this, however the major part I am struggling with is getting some coordinates in x and y that I can use to position the popover...

For reference here is a JSFiddle Fiddle I am working on.. http://jsfiddle.net/tarnfeld/Xefdb/3/

To get the main functionality working I have a little red span that I'd like to move to the caret position (the little | symbol as your typing) so I can further extend this to be awesome autocomplete love.

Any help would be appreciated :)

Thanks!!

PS: I have found answers like this Twitter-style autocomplete in textarea but they dont pop up under the @ char position...

Community
  • 1
  • 1
tarnfeld
  • 24,994
  • 39
  • 109
  • 145

2 Answers2

1

This seems to be pretty complicated. Basically, you have to get the current character position and convert it to X/Y coordinates.

I found the following links which might help you:

Calculating the x/y position is the tricky part. Both solutions (second and third link) create temporary elements (<div> or <textarea>) and fill them succesively with text calculating their height/width.

HTH.

Community
  • 1
  • 1
MartinStettner
  • 28,001
  • 14
  • 77
  • 104
  • This looks like an interesting idea.. i'll take a look! My other thought was to use contenteditable then wrap the last char with a and use jquery to get that elements absolute position... – tarnfeld Oct 08 '11 at 09:28
0

WooHoo!

So, with some reading and hacking I got this working.. You can take a look here (please read the message at the top!) http://jsfiddle.net/Xefdb/9/

I havn't yet tried it in IE so if anyone could and if it doesnt work properly send me a screenshot @tarnfeld that'd be awesome.

Here's a quick intro to how it works:

  • Get the caret position
  • Duplicate the editable wrapper and place it in the same place as the real editable wrapper
  • Wrap the character you just wrote in a span
  • Use jQuery to get the spans absolute position
  • Remove the duplicated wrapper
  • Position the element you wish to track the caret at the x/y of the span you just worked out.

If anyone can find a nicer way to do this please let me know!

PS. It should deal with scrolling too!

tarnfeld
  • 24,994
  • 39
  • 109
  • 145