JavaScript – Simple Keyboard Control

Contoh sederhana buat keyboard control di Javascript 😀

<!DOCTYPE html>
<html>
<head>
<title>Keyboard Controlled Red Box</title>
<meta charset=”utf-8″>
<style type=”text/css”>
DIV#box {
position: fixed;
width: 64px;
height: 64px;
background: red;
}
</style>
<script type=”text/javascript”>
x = 50;
y = 100;
function place_box() {
box.style.left = x + “px”;
box.style.top = y + “px”;
}
function key_handler(e) {
if (e.shiftKey || e.controlKey || e.metaKey || e.altKey) {
return true;
}
if (e.keyCode == 39) { // right
x += 10;
} else if (e.keyCode == 37) { // left
x -= 10;
} else if (e.keyCode == 38) { // up
y -= 10;
} else if (e.keyCode == 40) { // down
y += 10;
} else {
return true;
}
place_box();
return false;
}
</script>
</head>
<body onLoad=”place_box()” onKeyDown=”return key_handler(event)”>
<p>Use the cursor keys to move the red box.
<div id=”box”></div>
</body>
</html>