Skip to content

Commit

Permalink
Fix cell indexing and clicking bug. Closes #3.
Browse files Browse the repository at this point in the history
  • Loading branch information
rossant committed Mar 19, 2024
1 parent 778e153 commit 09d4b9a
Showing 1 changed file with 14 additions and 7 deletions.
21 changes: 14 additions & 7 deletions scripts/grid.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,8 @@ class Grid {

_createCell(i) {
let cell = document.createElement('div');
let row = Math.floor(i / this.rows);
let col = i % this.rows;
cell.addEventListener("click", (e) => {
if (this._onClick) this._onClick(row, col);
});
let row = Math.floor(i / this.cols);
let col = i % this.cols;
cell.title = `${row}, ${col}`;
this.gridTable.appendChild(cell);
}
Expand All @@ -47,6 +44,13 @@ class Grid {
this.gridTable.addEventListener("keydown", (e) => {
if (this._onKeyboard) this._onKeyboard(e.key);
});

this.gridTable.addEventListener("click", (e) => {
let coords = e.target.title;
let [row, col] = coords.split(", ").map(Number);
console.log(`Clicked on cell: (${row}, ${col}).`);
if (this._onClick) this._onClick(row, col);
});
}

onClick(f) {
Expand Down Expand Up @@ -111,8 +115,11 @@ class Grid {
cell(i, j) {
i = Math.floor(i);
j = Math.floor(j);
if (0 <= i && i < this.rows && 0 <= j && j < this.cols)
return this.gridTable.children[i * this.rows + j];
let cell = null;
if (0 <= i && i < this.rows && 0 <= j && j < this.cols) {
cell = this.gridTable.children[i * this.cols + j];
}
return cell;
}

bgcolor(i, j, r, g, b) {
Expand Down

0 comments on commit 09d4b9a

Please sign in to comment.