Skip to content

Instantly share code, notes, and snippets.

@radzhome
Created March 25, 2016 19:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save radzhome/a52ae8f1361005c219e6 to your computer and use it in GitHub Desktop.
Save radzhome/a52ae8f1361005c219e6 to your computer and use it in GitHub Desktop.
N by N Grid JS
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>P2</title>
<style type="text/css">
table.gridTable, table.gridTable td { border: 1px solid black; }
.u-paddedBottom { padding-bottom: 15px; }
</style>
</head>
<body>
<div id="ColorBox" class="u-paddedBottom">
Color Box
<table>
<tr> <!-- could set using classes, could create random colors here each time -->
<td style="background:red" onclick="setPickedColor(this)">R</td>
<td style="background:green" onclick="setPickedColor(this)">G</td>
<td style="background:blue" onclick="setPickedColor(this)">B</td>
<td style="background:yellow" onclick="setPickedColor(this)">Y</td>
<td style="background:greenyellow" onclick="setPickedColor(this)">_</td>
<td style="background:beige" onclick="setPickedColor(this)">_</td>
<td style="background:bisque" onclick="setPickedColor(this)">_</td>
<td style="background:aqua" onclick="setPickedColor(this)">_</td>
</tr>
</table>
</div>
<div class="u-paddedBottom">
<label for="GridLayoutY">Grid Layout</label>
<input type="number" id="GridLayoutY" value="2"/>
<label for="GridLayoutX">X</label>
<input type="number" id="GridLayoutX" value="2"/>
<input type="button" value="Generate" onclick="drawGrid()"/>
</div>
<div id="GridContainer"></div>
<script>
var pickedColor = 'white';
function setPickedColor(element) {
pickedColor = element.style.background;
}
function switchColors(element) {
element.style.background = pickedColor;
}
var drawGrid = function () {
var gridLayoutX = parseInt(document.getElementById('GridLayoutX').value) || 0,
gridLayoutY = parseInt(document.getElementById('GridLayoutY').value) || 0;
var $gridBoxContainer = document.getElementById('GridContainer');
var gridBoxContent = '<table class="gridTable">';
for (var i = 0; i < gridLayoutY; i++) {
gridBoxContent += '<tr>';
for (var j = 0; j < gridLayoutX; j++) {
gridBoxContent += '<td id="' + i + 'x' + j + '" onclick="switchColors(this);">X</td>';
}
gridBoxContent += '</tr>';
}
gridBoxContent += '</table>';
$gridBoxContainer.innerHTML = gridBoxContent;
};
drawGrid();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment