This JavaScript program shows how to handle left and right arrow key events. Pressing the left arrow key will turn the rectangle red. Pressing the right arrow key will turn the rectangle blue. Pressing any other key will turn the rectangle green.
<!DOCTYPE html> <html> <head> <title>XoaX.net's Javascript Keyboard Event Example</title> <script type="text/javascript" src="XoaXKeyboardEvent.js"></script> </head> <body> <div id="myrect" style="width: 300px; height: 200px; margin: 50px;"></div> </body> </html>
var qpRect = null;
function KeyHandler(qKeyEvent) {
var iKeyDown = 0;
var iLeftArrow = 37;
var iRightArrow = 39;
if (qKeyEvent) {
iKeyDown = qKeyEvent.which;
} else {
iKeyDown = window.event.keyCode;
}
if (iKeyDown === iLeftArrow) {
qpRect.style.backgroundColor = '#ff0000';
} else if (iKeyDown === iRightArrow) {
qpRect.style.backgroundColor = '#0000ff';
} else {
qpRect.style.backgroundColor = '#00ff00';
}
return false;
}
function Initialize() {
qpRect = document.getElementById('myrect');
qpRect.style.backgroundColor='#888888';
document.onkeydown = KeyHandler;
}
window.onload = Initialize;
© 20072026 XoaX.net LLC. All rights reserved.