Reputation: 1110
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?
Upvotes: 0
Views: 520
Reputation: 104775
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;
Upvotes: 2
Reputation: 33163
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>
Upvotes: 3