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
  • 135,913
  • 89
  • 401
  • 325
Mattias
  • 1,092
  • 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
  • 32,246
  • 20
  • 88
  • 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
  • 102,126
  • 13
  • 159
  • 155