I’ve been trying to program a pingpong game without jQuery (challenge from Software Design teacher), and am planning on using onkeypress to move the paddles. However, I’m not sure how to attach a specific key to the function specified in the event handler.
It’s not terribly relevant, but here’s my code:
HTML:
<div id="Paddle1" class="paddle" onkeypress="PaddleMovement1(event)"></div>
<div id="Paddle2" class="paddle" onkeypress="PaddleMovement3(event)"></div>
JavaScript:
var PaddleMovement1 = function(){
document.getElementById('Paddle1Up').style.animationPlayState="running";
setTimeout(Paddle1Stop1, 25)
var Paddle1Stop1 = function(){
document.getElementById('Paddle1Up').style.animationPlayState="paused";
};
};
var PaddleMovement2 = function(){
document.getElementById('Paddle1Down').style.animationPlayState="running";
setTimeout(Paddle1Stop2, 25)
var Paddle1Stop2 = function(){
document.getElementById('Paddle1Down').style.animationPlayState="paused";
};
};
var PaddleMovement3 = function(){
document.getElementById('Paddle2Up').style.animationPlayState="running";
setTimeout(Paddle2Stop1, 25)
var Paddle2Stop1 = function(){
document.getElementById('Paddle2Up').style.animationPlayState="paused";
};
};
var PaddleMovement4 = function(){
document.getElementById('Paddle2Down').style.animationPlayState="running";
setTimeout(Paddle2Stop2, 25)
var Paddle2Stop2 = function(){
document.getElementById('Paddle2Down').style.animationPlayState="paused";
};
};
Finally, the complete thing can be found in this jsfiddle:
keypressis only fired for keypresses that result in typeable characters, not other keys. To detect other keys, usekeydownandkeyup. This should be fairly clear from the specification:This page is a handy guide to the madness that is keyboard events in JavaScript across browsers…
Separately, for your purposes I’d probably trap the events on
documentrather than on a specific element (keydownandkeyupbubble, so that works).For example:
Live Copy | Source