There are tons of options out there for doing autocompletion. Most of them seem to work on the first few letters that are typed.
In Google Plus, an autocomplete option drops down soon after typing @
, no matter where it occurs in the form field, and uses the letters immediately following @
to guide the autocomplete. (It also looks quite nice!)
Has anybody shared code to do this sort of thing?
Does anybody have any pointers for trying to implement a toy version of this (e.g. in jQuery)?
I wrote a bootstrap plugin for this. It works no matter where the @ occurs in the form field. It's for ContentEditable divs rather than text area: http://sandglaz.github.com/bootstrap-tagautocomplete/
This is possible with jQueryUI's autocomplete widget. Specifically, you can adapt this demo to satisfy your requirement. Here's an example:
And here it is working: http://jsfiddle.net/UdUrk/
Let me know if you need any more information (such as how to make it work with a remote datasource).
Update: Here's an example using a remote datasource (StackOverflow's API): http://jsfiddle.net/LHNky/. It also includes custom display of autocomplete suggestions.
To expatiate Andrew Whittaker's answer a bit, the
source
option of jQuery UI Autocomplete is used to specify an array containing the items that are to be displayed in the drop-down list once the widget is triggered. It can be defined as such an array, a function that returns such an array, or a URL to a resource which produces such an array.If
source
is defined as an function, the parameters of the function,request
andresponse
, can be used to help compose its return array and supply it to the widget, respectively.request
in particular is of interest to you, since its member,term
contains the value of the input element to which the widget is affixed, at the time the function is invoked.See where I'm going with this? Its pretty simple, parse
request.term
for the text between the@
symbol of interest and the cursor, and use that text to create the array to supply to the widget. You'll need to do a little work (or employ some ready-made functions) to be able to locate the cursor reliably in a cross-browser compatible way, however.Check out Mentionator if you're looking for an existing plug-in that provides the functionality you're trying to emulate. It is well structured, easy to follow, and copiously commented, so you should have little trouble understanding how to take the approach I've described. It is also maintained by yours truly:) .
you can use autocomplete search event to detect if the text is having @ in it. If it is not @ then just return false and autocomplete will not work.
eg : $( ".selector" ).autocomplete({ search: function(event, ui) { ... } });
I wrote a jQuery plugin based on the jQuery UI autocomplete functionality. Here is my solution:
http://www.hawkee.com/snippet/9391/
You call it like this: