views:

131

answers:

1

From my recent question, I use KeyPress event for detecting '@' character in rich text editor. By the way, I just found that KeyPress event in other browser like Firefox 3.5 and Google Chrome 4 do not return any position in this event.

For clarify, my position is a distance from top or left of screen. In this case, it should be distance between new character and IFrame screen. In IE, I can find it in event object like x, y, offsetX, offsetY.

Is possible to find position from last character that was typed? Or you have any other idea for finding it.

Thanks,

A: 

For an input/textarea, you can find out the current position of the cursor using input.selectionStart/selectionEnd. If it was a simple insertion keypress that will be just ahead of the new character. (Don't rely on it, there are browsers that support neither the IE nor the Mozilla extensions.)

If your ‘rich text editor’ is a HTML designMode/contentEditable thing (the horror!) then I would guess you'd have to use window.getSelection() to read the position of the cursor. This is even worse:

if (window.getSelection) {
    var selection= window.getSelection();
    if (selection) {
        if (selection.getRangeAt) { // Mozilla
            if (selection.rangeCount>=1) {
                var range= selection.getRangeAt(0);
                return [range.startContainer, range.startOffset];
            }
        } else if (selection.focusNode) { // Webkit
            return [selection.focusNode, selection.focusOffset];
        }
    }
}

Seems to work with designMode for Mozilla, haven't tested in the others.

bobince
Please read my updated question. I think your answer will return position that is a number of characters from the beginning of container.
Soul_Master
Argh, screen position is even worse! You could theoretically do it by calling `textnode.splitNode` to isolate the character in question, wrap it in a `<span>`, measure the screen position of the span then remove it and re-join the text, but that's really horrible and slow.
bobince