document.onkeyup triggers when it shouldn't
Posted
by vonkow
on Stack Overflow
See other posts from Stack Overflow
or by vonkow
Published on 2010-04-01T20:06:39Z
Indexed on
2010/04/01
20:23 UTC
Read the original article
Hit count: 323
JavaScript
|keyboard-events
So I have the following code, which should append 'true' to the div "test" every 25ms as long as key 68 (the d key) is being pressed, right?
<html>
<body>
<div id="test"></div>
<script type="text/javascript">
var key=false;
var keyDown=function(e) {
if (e.keyCode==68) {
key=true;
}
}
var keyUp=function(e) {
if (e.keyCode==68) {
key=false;
}
}
document.onkeydown=keyDown;
document.onkeyup=keyUp;
var run=function() {
document.getElementById('test').appendChild(document.createTextNode(key+'\n'));
t = setTimeout('run()', 25);
}
var t = setTimeout('run()', 25);
</script>
</body>
</html>
Save the code, load it in a browser and hold down on the d key. If I'm not crazy, you'll see that it occasionally appends 'false' even though the d key was never released. (I've tried this in FF and Chrome in Linux and Vista). Anybody happen to know why, or have a workaround?
© Stack Overflow or respective owner