0

I am trying to write a web page that can catch onkeyup events.

It uses document.write("..."); to print the keycode each time.

However it only works once, the second time I use it, the window does not update.

Here is the code:

document.onkeyup = function checkKeys(event) {
    var keyCode = event.which || event.keyCode;
    document.write(keyCode);
};

Why does this only catch the event once?

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
Mattias
  • 1,110
  • 1
  • 11
  • 26

2 Answers2

3

Don't use document.write(). It's wiping the page clean, along with the onkeyup handler. Create an element on the page and update the element's contents.

document.onkeyup = function checkKeys(event) {
    var keyCode = event.which || event.keyCode;
    document.getElementById( 'results' ).innerText = keyCode;
};

HTML:

<div id="results"></div>
Community
  • 1
  • 1
JJJ
  • 32,902
  • 20
  • 89
  • 102
2

document.write(keyCode); is overwriting the page each time with the new keycode, you need to append to the document, preferably a div on the page:

<div id="keyupDiv"></div>

document.getElementById("keyupDiv").innerHTML += keyCode; 
tymeJV
  • 103,943
  • 14
  • 161
  • 157