views:

36

answers:

1

Hello

I'm trying to create a div with contenteditable like the Facebook status update. Then I mean I want to show an autocomplete box when the user have written @.

How would you do that. Currently I'm just playing with keypress and check if the keycode = 64. Somehow that works, but it doesn't validate if there's a space before the alfa, or if the user has unfocused the box, then focused it again.

Any ideas? Or do you know about any plugin that works something like that?

Tnx

A: 

I'd probably do it with keypress too.

but we need to check the cursor position to check the character before the '@'.

here's the function I used from http://javascript.nwbox.com/cursor_position/cursor.js

function getSelectionStart(o) {
  if (o.createTextRange) {
    var r = document.selection.createRange().duplicate();
    r.moveEnd('character', o.value.length); 
    if (r.text == '') return o.value.length
      return o.value.lastIndexOf(r.text);
    } else { 
      return o.selectionStart;
    }
}

then with jquery I wrote this keypress callback function:

txt.keypress(function(event) {
    if (event.which == 64) {
        var index = getSelectionStart(this)
        var prevChar = txt.val().substring(index - 1, index);
        // now you can check if the previous char was a space
    }
});
ricecake5
Thanks, at leas somewhere to start :)
Terw