Answer the question
In order to leave comments, you need to log in
Why can't I connect keyboard input processing?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"
<title>GAME</title>
<link rel="stylesheet" href="style.css" type="text/css" media="screen" />
<script language="javascript" src="script.js"></script>
</head>
<body>
<div id="matrix"></div>
</body>
</html>
function createMatrix()
{
var matrix = document.getElementById('matrix');
var n = 400;
for (var i = 0; i < n; i++)
{
var div = document.createElement('div');
div.className = 'cell';
matrix.appendChild(div);
}
};
function setCell(row, col, val){
var cell = ((row * 20) + col) - 21;
if (val == true){
document.getElementById('matrix').children[cell].style.backgroundColor = 'red';
}
else {
document.getElementById('matrix').children[cell].style.backgroundColor = '';
}
};
function randomCell(){
var cell = Math.floor(Math.random() * 399) + 1;
document.getElementById('matrix').children[cell].style.backgroundColor = 'black';
};
function handler(e){
switch (e.keyCode) {
case 39: //right
if(col < 20){
setCell(row, col, false);
col++;
setCell(row, col, true);
}
else{
setCell(row, col, false);
col = 1;
setCell(row, col, true);
}
break;
}
};
window.onload = function()
{
createMatrix();
document.getElementById('matrix').onkeydown = function(){
handler(e);
};
setCell(1, 1, true);
randomCell();
};
#matrix
{
width: 400px;
height: 400px;
border-top: 1px solid #999;
border-left: 1px solid #999;
}
#matrix .cell
{
float: left;
width: 19px;
height: 19px;
border-bottom: 1px solid #999;
border-right: 1px solid #999;
}
Answer the question
In order to leave comments, you need to log in
In your code, you don't place a listener on the input event anywhere.
Another very bad tone is to drag C++/C# formatting style into JS and CSS .
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question