views:

1158

answers:

1

I am dealing with a content editable div and I need to deal with capturing key strokes both before and after the character has been added to the div.

My understanding of capturing vs. bubbling is that the event gets captured at the highest level in the dom tree first then passes it down, while for bubbling it starts at the lowest level and bubbles up the tree.

Based on that understanding, I thought that if I added an event listener at the capturing phase, the content of the editable div would reflect the text from before the keystroke had been sent. If I add an event listener at the bubbling phase, the div's text content will contain the character I just typed.

This doesn't seem to be the case though: whether the event listener is added at the capturing or bubbling phase, the div's content never includes the most recently typed character.

Here is a simple test case to try it out:

<div id="captureTest" contentEditable='true' style='height: 30px; width: 400px; border-style:solid; border-width:1px'></div>

<script type="text/javascript">
    var div = document.getElementById('captureTest');
    div.addEventListener("keydown", function() {alert('capture: ' + this.innerHTML)}, true);
    div.addEventListener("keydown", function() {alert('bubble: ' + this.innerHTML)}, false);
</script>

I would expect the output of the second function to include the div's new text after typing a character, but this doesn't seem to be the case.

My question is: is there a way to capture a keystroke event from a content editable div and get the content as it will be after the key is typed? I need this for implementing typeahead functionality.

I know that I can stop the event and then use executeCommand('insertHTML'), but this breaks down when handling deletions, backspaces, pastes and other types of insertions, so that is not a solution.

I am testing this in Firefox 3. I know that IE doesn't have an addEventListener method.

Thanks for any suggestions!

+2  A: 

You need 2 different callbacks, one for keydown and another with keyup or keypress (which is only fired when the element registered both the keydown + keyup).

Seb