JSFiddle - React, Tailwind, and code Playground
HTML
<table border="1">
<tr>
<td></td>
<td id="up"></td>
<td></td>
</tr>
<tr>
<td id="left"></td>
<td id="center"></td>
<td id="right"></td>
</tr>
<tr>
<td></td>
<td id="down"></td>
<td></td>
</tr>
</table>
<a id="ball">●</a>
CSS
td {
height:20px;
width:20px;
}
#center {
background-color:red;
}
#ball {
position:absolute;
font-size:3em;
}
JavaScript
var x = 0;
var y = 0;
var dirs = {
left: false,
top: false,
right: false,
bottom: false
};
$(document).keydown(function(e){
switch (e.keyCode) {
case 37: dirs.left = true; return false;
case 38: dirs.top = true; return false;
case 39: dirs.right = true; return false;
case 40: dirs.bottom = true; return false;
}
});
$(document).keyup(function(e){
switch (e.keyCode) {
case 37: dirs.left = false; return false;
case 38: dirs.top = false; return false;
case 39: dirs.right = false; return false;
case 40: dirs.bottom = false; return false;
}
});
var checkLeft = function() {
if (dirs.left) {
$("#left").css( "background-color", "red" );
x--;
} else {
$("#left").css( "background-color", "#fff" );
}
}
var checkRight = function() {
if (dirs.right) {
$("#right").css( "background-color", "red" );
x++;
} else {
$("#right").css( "background-color", "#fff" );
}
}
var checkTop = function() {
if (dirs.top) {
$("#up").css( "background-color", "red" );
y--;
} else {
$("#up").css( "background-color", "#fff" );
}
}
var checkBottom = function() {
if (dirs.bottom) {
$("#down").css( "background-color", "red" );
y++;
} else {
$("#down").css( "background-color", "#fff" );
}
}
var moveBall = function() {
$("#ball").css({
"margin-left": x*10,
"margin-top": y*10
});
}
setInterval(function() {
checkLeft();
checkRight();
checkTop();
checkBottom();
moveBall()
}, 50);