Having searched high and low for a decent @mention/#tag contenteditable div solution, I'm embarking on building one.
In a keyup event handler, I am using the range selection trick to get the current cursor position from which I am able to determine the last two characters entered. I'm using it, for instance, to see if a space followed by an @ has been entered to know when to invoke autocomplete. I need to be able to reliably get the current cursor position so I can handle all the annoying cases of backspacing, using the arrow keys, clicking in the area.
The problem I am having is that in my keyup handler, the keycode I am getting in the event matches what I've typed but the selection seems to be lagging when I type fast enough.
For instance, see this http://jsfiddle.net/puMCX/
$( '#test' ).bind( 'keyup', function( event )
{
var range = window.getSelection().getRangeAt(0);
console.log( "event.which char '" + String.fromCharCode( event.which ) + "' character from range :'" + $( range.startContainer ).text().charAt( range.startOffset - 1 ) + "'" );
});
Click on the TEST and type in something quickly. If you type reasonably fast you will notice that the keycode and selection do not match.
fiddle.jshell.net:25event.which char 'T' character from range :'i'
fiddle.jshell.net:25event.which char 'H' character from range :'s'
fiddle.jshell.net:25event.which char 'I' character from range :'s'
fiddle.jshell.net:25event.which char 'S' character from range :'s'
Typing slowly it works just fine.
It seems the selection is getting updated before the keyup events have a chance to fire.
So the question is, how can I accurately determine the position of the cursor in a contenteditable div (and the characters surrounding said cursor position) when someone types really fast? Or even better, is there a better way to do this in a rigorous cross browser way that will accomplish the same goal?
Most other @mention/tagging plugins I've tried suffer from the same problem. Facebook, however, does not. No matter how fast I type it works as it should, so clearly there is a better way of doing it.
I am testing using Chrome under Linux.