Skip to content

Instantly share code, notes, and snippets.

@ricealexander
Last active November 26, 2018 18:05
Show Gist options
  • Save ricealexander/4fb69b5aa6670114665356654dda1429 to your computer and use it in GitHub Desktop.
Save ricealexander/4fb69b5aa6670114665356654dda1429 to your computer and use it in GitHub Desktop.
These snippets build a grid with HTML and associate the cells in a 2-dimensional array
// Inspired by @kokokonotsu
/// https://github.com/kokokonotsu/Cells-and-Grids
const
gridContainer = 'body', // selector for our HTML grid
columnCount = 26, // number of columns
rowCount = 20; // number of rows
// Generate the grid
function makeGrid(x,y) {
const HTMLgrid = ('<div class="row">' + '<div class="cell"></div>'.repeat(x) + '</div>').repeat(y);
document.querySelector(gridContainer).innerHTML = HTMLgrid;
}
// Build a 2-dimensional array associated with the grid
function setArray() {
const
rows = Array
.from(document.querySelectorAll(`${gridContainer} .row`))
.reverse(), /// dom elements are loaded from top to bottom, which inverts our y-axis
x = rows[0].children.length,
y = rows.length,
thisArray = [];
for (let i=0; i<x; i++) { /// magic that associates each cell in the 2D Array
thisArray[i] = new Array(y);
for (let j=0; j<y; j++) {
thisArray[i][j] = rows[j].children[i];
}
}
return thisArray;
}
// let's try it out!
makeGrid(columnCount, rowCount);
let cellsArray = setArray();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment