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
  • 123,728
  • 82
  • 382
  • 321
Mattias
  • 1,062
  • 1
  • 11
  • 25

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
  • 31,545
  • 20
  • 84
  • 99
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
  • 99,730
  • 13
  • 150
  • 152