Mkz
Mkz

Reputation: 1

What is the most efficient way to create a clickable grid with html/js?

I'm trying to set up a minesweeper-ish kind of game I can share with my Dad over the web. How would I use a loop to create that grid and make each index at a certain coordinate that I can manipulate? Thanks everyone.

Upvotes: 0

Views: 5413

Answers (2)

Nate Anderson
Nate Anderson

Reputation: 690

This will give you some click events, reporting back the column and row.

css:

td {
    border: black solid 1px;
}

html:

<table class="table"></table>

javascript:

$('.table').on('click', 'td', function () {
    console.log($(this).attr('data-row'));
    console.log($(this).attr('data-column'));
})

var columns = 10, rows = 10

function createGrid(columns, rows) {
    var table = $('.table');

    for (var i = 0; i < rows; i++) {
        var row = $('<tr>');
        table.append(row)
        for (var j = 0; j < columns; j++) {
            var cell = $('<td>')
            cell.attr('data-row', i);
            cell.attr('data-column', j)
            row.append(cell);
        }
    }
}
createGrid(columns, rows);

Upvotes: 2

Tom Mettam
Tom Mettam

Reputation: 2963

You can use a multi-dimensional array (an array of arrays).

var gridWidth = 10;
var gridHeight = 10;
var grid = [];
for(var y = 0; y < gridHeight; y++)
{
    grid.push([]);
    for(var x = 0; x < gridWidth; x++)
    {
        grid[y].push(0);
    }
}

You now have a 10x10 grid, which you can access via grid[x][y]

Representing this on the page, in HTML, depends on the framework you are using. If you want to do it with raw javascript, you could perhaps output a table.

document.write('<table>');
var gridWidth = 10;
var gridHeight = 10;
var grid = [];
for(var y = 0; y < gridHeight; y++)
{
    document.write('<tr>');
    grid.push([]);
    for(var x = 0; x < gridWidth; x++)
    {
        document.write('<td onclick="alert(\'clicked\');">');
        grid[y].push(0);
        document.write('</td>');
    }
    document.write('</tr>');
}
document.write('</table>');

Upvotes: 3

Related Questions