autocomplete middle of a textarea selector javascript jquery
I have seen how t开发者_如何学Goo have multiple autocompletes in a single textarea, but what I want to due is have something that can select a term in the middle of the textarea, or more precisely wherever the cursor is/was in the textarea. Most solutions I have seen only work if the user is working on the end of the input string. I would like to have something along the lines of being able to start with the string: "@George stepped on #foot." then go back to the middle of the string and start typing to change it to this: "@George stepped on @Fredrick's #foot. according to @Mary" and have @Fredrick and @Mary each separately show up as an autocomplete option.
for the specific use I want this functionality for, the autocomplete will happen on character strings that start with either a "@" or a "#" symbol, but they will not necessarily be the first or last of the given symbol.
I am using javascript and jquery-ui for this task. this is for use on mobile devices so the position of the autocomplete will always just be at the bottom of the text area.
I'm actually implementing something very similar. I've looked at Google+ and they're using contenteditable
for Chrome and some iframe
hybrid for Firefox.
I've had moderate success with rangy for getting the current selection.
Things I haven't solved yet:
- Properly detecting when the users starts typing @ or #, this is harder than it seems, especially if you're injecting HTML in the input area.
- Getting the x,y position of the current selection so you can position the auto-complete suggestions. Supposedly rangy can do it already but it's not in the official release yet (there is a working demo though).
I found out that I can do pretty much every thing I wanted by using the textarea.selectionStart value, and then cycling back from that index to the start of the tag, and then using selectionStart again to find the end of the tag. the conditions for when to stop increasing/decreasing the indices for the start and end of the tag can be a little complex, for mine it checks that it does not go beyond the start/end of the textarea text, or for the start of a tag with "#", "@" or a space. to replace the text when you have made your selection uses pretty much the same process to find the text, and then replaces the text with the selected tag. and sets the cursor after replacing the text, by setting the cursor to the start position of the tag offset by the length of the selected tag.
精彩评论