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>

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s