I have developed a system in PHP which processes #hashtags like on Twitter. Now I'm trying to build a system that will suggest tags as I type. When a user starts writing a tag, a drop-down list should appear beneath the textarea with other tags that begin with the same string.
Right now, I have it working where if a user types the hash key (#) the list will show up with the most popular #hashtags. When a tag is clicked, it is inserted at the end of the text in the textarea. I need the tag to be inserted at the cursor location instead. Here's my code; it operates on a textarea with class "facebook_status_text" and a div with class "fbssts_floating_suggestions" that contains an unordered list of links. (Also note that the syntax [#my tag] is used to handle tags with spaces.)
maxlength = 140;
var dest = $('.facebook_status_text:first');
var fbssts_box = $('.fbssts_floating_suggestions');
var t = setTimeout(function() { fbssts_box.hide(); }, 250);
});
When the user types, I also need get the text in the textarea from the beginning to the cursor, and pass it (presumably via POST) to /fbssts/load/tags. The PHP back-end will process this, figure out what tags to suggest, and print the relevant HTML. Then I need to load that HTML into the .fbssts_floating_suggestions div at the cursor location.
Ideally, I'd like to be able to do this:
var newSuggestions = load('/fbssts/load/tags', {text: dest.getTextBeforeCursor()});
Right now, my main hold-up is dealing with the cursor location. I've researched for the last two hours, and just ended up more confused. It appears that cursor location is not dealt with in the same way across browsers, and potential solutions that I have found are difficult to adjust to jQuery. The code that I end up with will be published under the GPL 2, so if I have to use a plugin I would strongly prefer that it be a GPL one.
Thanks!
EDIT:
With help from people in #jquery on IRC, I arrived at this solution for the jQuery that matches the functions I was pining for above: