1

I'm trying to run a script on an input text box that populates a div. The snippet is like so:

<input type="text" id="control" value="" />
<div id="displaydiv"></div>
<script>
document.getElementById("control").onkeydown = function() {
document.getElementById("displaydiv").innerHTML = this.value;   
}
</script>

The problem here is that there is a lag of one character, i.e. if I type 'a', nothing shows up. When I type 'b', the previous 'a' shows up and so on. I tried replacing the onkeydown with onkeyup, and there is still a bit of a lag. How do I get the div to match the input text box in real time, without refreshing the page and/or losing focus on the input box?

Thanks for looking.

1
  • 1
    "I tried replacing the onkeydown with onkeyup, and there is still a bit of a lag" - welcome to web programming. onKeyDown is as fast as you're going to get ... there is no "beforeTheUserPressesAKey" event. Commented Jun 6, 2012 at 0:16

1 Answer 1

2

That is because onkeydown triggers before the key has added its value to the input. Use onkeyup instead. It will work the way you are after.

Edit: Not sure if I missed the speed thing, if you edited your question, but the lag you are seeing is unavoidable. It is as close to "real-time" as you are going to get. It's really not even that bad, less than half a second when I check it in a fiddle

Edit2: Just to satisfy my curiosity, I checked the performance against KnockoutJS's databinding, with the one input updating a div text via knockout, and another div via your script. The performance is identical. I was actually a bit surprised knockout didn't introduce any noticable overhead. Here is the fiddle

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.