views:

600

answers:

3

I have a situation where I need to intercept every key thats being pressed in to a contentEditable div. But when the keypress event happens, if I do,

document.getElementById("divEditor").innerHTML

I cannot get the full text (does not have the last character pressed)

Also, keyup event doesn't fire for continuous keypresses. What can I do to have a key event that has the entire value?

+1  A: 

keyup is the only event that gets to see the post-keypress state.

One approach is to trap keydown and set a timeout to do some processing after the keypress:

input.onkeydown= function() {
    setTimeout(function() {
        // do something
    }, 1);
};

However if it is also possible to do edits without a keypress (and it usually is, via drag-and-drop and menu items like cut-and-paste), no amount of checking for key events will help. Instead, you must simply poll the state to see if it has changed. You can back this up with an onkeyup handler or onkeydown timeout to make that particular case update quicker.

var oldstate= input.value;
function checkState() {
    if (input.value!=oldstate) {
        // do something
        oldstate= input.value;
    }
}
setInterval(checkState, 1000);
input.onkeyup= checkState;

(This uses an input element for simplicity, but is equally applicable to contentEditable.)

bobince
A: 

It seems the best way would be to have an INPUT field (position:absolute; left:-1000px) and add all 3 events (keydown keypress keyup) to it.

Now you can use the value of this input field, CTRL + Z works and you can paste values.

All you have to do than is to setFocus to the input field.

var user_action = function ()
{
   document.getElementById("divEditor").innerHTML =    document.getElementById("myhiddenInput").value;
};

document.getElementById("myhiddenInput").onchange = user_action;
document.getElementById("myhiddenInput").onkeydown  = user_action;
document.getElementById("myhiddenInput").onkeyup    = user_action;
document.getElementById("myhiddenInput").onkeypress = user_action;

document.getElementById("divEditor").onclick = document.getElementById("myhiddenInput").focus;
Ghommey
A: 

what about onblur()? you would need two functions, your key press function, and then an onblur() call when focus has left the text box. This should give you access to the rest of the text.

andrewWinn