JSFiddle - React, Tailwind, and code Playground
by mlms13
HTML
<div id="container"></div>
<p id="console"></p>
CSS
#container {
border: 2px solid #777;
display: table;
overflow: auto;
}
.box {
border: thin solid #bbb;
float: left;
height: 24px;
width: 24px;
}
.box.first {
clear: left;
}
#selected {
background: #069;
}
#console {
clear: both;
height: 80px;
margin-top: 30px;
overflow: auto;
}
JavaScript
$(document).ready(function(){
var grid = new Grid(10,10);
grid.DrawBoxes();
grid.SelectRandom();
$(document).bind('keydown', function(e) {
e.preventDefault();
var key = (e.which);
switch (key) {
case 37:
grid.MoveLeft();
break;
case 38:
grid.MoveUp();
break;
case 39:
grid.MoveRight();
break;
case 40:
grid.MoveDown();
break;
default:
$('#console').append('Invalid key pressed.<br />');
}
});
});
function Grid(height, width)
{
this.height = height;
this.width = width;
this.area = height * width;
this.DrawBoxes = DrawBoxes;
this.currentBox = -1;
this.DeselectAll = DeselectAll;
this.Select = Select;
this.SelectRandom = SelectRandom;
this.MoveLeft = MoveLeft;
this.MoveUp = MoveUp;
this.MoveRight = MoveRight;
this.MoveDown = MoveDown;
}
function DrawBoxes() {
var class;
for (i = 0; i < this.height; i++) {
for (j = 0; j < this.width; j++) {
class = j === 0 ? " first" : "";
$('#container').append('<div class="box' + class + '"></div>');
}
}
}
function DeselectAll()
{
$('.box#selected').attr('id', '');
}
function SelectRandom()
{
this.Select(Math.floor(Math.random() * this.area));
}
function Select(boxIndex)
{
this.DeselectAll();
this.currentBox = boxIndex;
$('.box').eq(boxIndex).attr('id', 'selected');
}
function MoveLeft ()
{
if (this.currentBox % this.width != 0) {
this.Select(this.currentBox - 1);
}
else {
$('#console').append('Can\'t move left.<br />');
}
}
function MoveUp ()
{
if (this.currentBox >= this.width) {
this.Select(this.currentBox - this.width);
}
else {
$('#console').append('Can\'t move up.<br />');
}
}
function...