Core JavaScript

Using Directional Key Controls

This JavaScript Reference section displays the code for an example program that shows how to create a directional control using key events. Use the W, A, S, and D keys to move the black square around the board below.

EventKeyDirection.html

<!DOCTYPE html>
<html>
<head>
    <title>XoaX.net's Javascript</title>
</head>
<body>
    <script type="text/javascript" src="EventKeyDirection.js"></script>
</body>
</html>

EventKeyDirection.js

var qBody = document.getElementsByTagName("body")[0];

var iX = 0;
var iY = 0;
var iCountX = 12;
var iCountY = 12;
var dWidth = 50;
var dHeight = 50;
var iPadding = 10;
var iBorder = 2;

var qContainerDiv = document.createElement("div");
qContainerDiv.style.backgroundColor = "#eeeeee";
qContainerDiv.style.border = (iBorder + "px solid #808080");
qContainerDiv.style.width = (iCountX*dWidth + 2*iPadding) + "px";
qContainerDiv.style.height = (iCountY*dHeight + 2*iPadding) + "px";
qContainerDiv.style.margin = "50px";
qContainerDiv.style.left = "0px";
qContainerDiv.style.top = "0px";
qContainerDiv.style.position = "absolute";
qBody.appendChild(qContainerDiv);

var qaaDivArray = null;
// Allocate the 2d array of divs
qaaDivArray = new Array(iCountX);
for (var i = 0; i < iCountX; ++i) {
	qaaDivArray[i] = new Array(iCountY);
}
// Allocate the divs
for (var j = 0; j < iCountY; ++j) {
	for (var i = 0; i < iCountX; ++i) {
		var qGridDiv = document.createElement("div");
		if (((i + j) % 2) == 0) {
			qGridDiv.style.backgroundColor = "#888888";
		} else {
			qGridDiv.style.backgroundColor = "#aaaaaa";
		}
		if ((i == iX) && (j == iY)) {
			qGridDiv.style.backgroundColor = "#444444";
		}
		qGridDiv.style.width = dWidth + "px";
		qGridDiv.style.height = dHeight + "px";
		qGridDiv.style.left = ((i*dWidth) + iPadding) + "px";
		qGridDiv.style.top = ((j*dHeight) + iPadding) + "px";
		qGridDiv.style.position = "absolute";
		qContainerDiv.appendChild(qGridDiv);
		qaaDivArray[i][j] = qGridDiv;
	}
}

document.onkeydown = function(e) {
	var iKeyW = 87;
	var iKeyA = 65;
	var iKeyS = 83;
	var iKeyD = 68;
	var iKeyCode = 0;
	if (e) {
		iKeyCode = e.which;
	} else {
		iKeyCode = window.event.keyCode;
	}
	switch (iKeyCode) {
		case iKeyW: {
			if (iY > 0) {
				--iY;
			}
			break;
		}
		case iKeyA: {
			if (iX > 0) {
				--iX;
			}
			break;
		}
		case iKeyS: {
			if (iY < iCountY - 1) {
				++iY;
			}
			break;
		}
		case iKeyD: {
			if (iX < iCountX - 1) {
				++iX;
			}
			break;
		}
		default: {
			break;
		}
	}
	// Rest the colors of the squares
	for (var j = 0; j < iCountY; ++j) {
		for (var i = 0; i < iCountX; ++i) {
			if (((i + j) % 2) == 0) {
				qaaDivArray[i][j].style.backgroundColor = "#888888";
			} else {
				qaaDivArray[i][j].style.backgroundColor = "#aaaaaa";
			}
			if ((i == iX) && (j == iY)) {
				qaaDivArray[i][j].style.backgroundColor = "#444444";
			}
		}
	}
}

 

Output

 
 

© 2007–2024 XoaX.net LLC. All rights reserved.