Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save P1xt/9dc13ab1a7ddfa3b5b8b to your computer and use it in GitHub Desktop.
Save P1xt/9dc13ab1a7ddfa3b5b8b to your computer and use it in GitHub Desktop.
Grid of green tiles, with diagonals in red

Grid of green tiles, with diagonals in red

Usually you see jQuery pulled in to manipulate the DOM. This is a Proof of Concept, drawing the grid exclusively by dynamically adding DOM elements on page load with JavaScript (using plain JS, no jQuery or other "helpers"). Clicking on a grid element will cause it to disappear, this is accomplished via a click handler which toggles the element's background style off onclick.

A Pen by P1xt on CodePen.

License.

window.onload = function() {
var i,
j,
section,
row,
cub,
gridsize = 20;
section = document.createElement("SECTION");
section.id = "main-grid"
for (i = 0; i < gridsize; i++) {
row = document.createElement("SECTION")
row.className = "row";
for (j = 0; j < gridsize; j++) {
if (i == j || i+j == 19) {
cub = document.createElement("DIV")
cub.className = "cub red";
} else {
cub = document.createElement("DIV")
cub.className = "cub green";
}
cub.addEventListener("click", function () {
this.className = "cub clicked";
});
row.appendChild(cub);
}
section.appendChild(row)
}
document.body.appendChild(section);
};
#main-grid {
margin: 30px 0 0 20px;
}
.row {
clear: both;
}
.cub {
float:left;
position: relative;
width: 44px;
padding: 0 0 44px 0;
margin: 1px;
overflow:hidden;
}
.green {
background-color: #008000;
}
.red {
background-color: #FF0000;
}
.clicked {
background: none;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment