From 09d4b9ac5155da29094f06adedd0f8bcd293f0e7 Mon Sep 17 00:00:00 2001 From: Cyrille Rossant Date: Tue, 19 Mar 2024 15:56:15 +0100 Subject: [PATCH] Fix cell indexing and clicking bug. Closes #3. --- scripts/grid.js | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/scripts/grid.js b/scripts/grid.js index 937d1c1..1fe9d55 100644 --- a/scripts/grid.js +++ b/scripts/grid.js @@ -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); } @@ -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) { @@ -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) {