How do I get the content of the div on a key press so that it also includes the text which was entered on that keypress?

StackOverflow https://stackoverflow.com/questions/16535636

Question

I have a contenteditable div and the user can enter or modify the text in it.I want to display the text in another div html code:

    <div contenteditable="true" id ="a1">
    </div>
    <div id="a2">
    </div>

the javascript code:

    var x=document.getElementById("a1");
    x.onkeypress=function(){
    var z= document.getElementById("a2");
    z.innerHTML=x.innerHTML;

    };

but it displays the content with one letter less than the actual data i have in the "a1" div or one letter more If I press the back-space key.I want to synchronize the content in both divs i.e. the modified text after this key press event.How do I achieve this?

Was it helpful?

Solution

You should use the onkeyup event instead of onkeypress . It's more realtime since it fires before keypress :)

var x=document.getElementById("a1");
x.onkeyup=function()
{
  var z= document.getElementById("a2");
  z.innerHTML=x.innerHTML;
};

OTHER TIPS

Use the onkeyup event instead. It kicks in when the key has been released, and the new key has been registered. Another problem with onkeypress is that it only works for printable characters, so it won't fire for backspace

try changing the x.onkeypress for x.onkeyup, since the action is taking place when you press the key, before the system has the key input

var x=document.getElementById("a1");
//use onkeyup to process the key after the input
x.onkeyup=function(){
    var z= document.getElementById("a2");
    z.innerHTML=x.innerHTML;
};

Here's this link for more reference

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top