lettda lettda - 6 months ago 90
Javascript Question

Making a dynamic grid with jquery

I'm trying to create a dynamic grid using jquery where it will eventually change with user input (i.e. 16x16, 32x32, etc). My logic is to create 16 rows and then 16 squares within each row, but I'm having trouble getting the squares to append the correct amount.

$(document).ready(function () {
for (var i = 0; i < 16; i++) {
$('.grid').append("<div class = 'row'></div>");
//$('.row').width(($('.square').width().val() * i);
//for (var i = 0; i < 16; i++) {
$('.row').append("<div class='square'></div>");
// }

Here is a link to what it looks like: https://lettda.github.io/EtchAsketch/


Moving your inner for loop outside of the outer for loop should create the proper amount of squares, as such:

for (var i = 0; i < 16; i++) {
    $('.grid').append("<div class = 'row'></div>"); // Each grid gets 16 rows

for (var i = 0; i < 16; i++) {
    $('.row').append("<div class='square'></div>"); // Each row gets 16 squares

Explicitly setting the width of the row is not necessary, as it will automatically be 16 times the width of your square plus any padding/margin you add. Note that all your squares would need display: inline-block; in the CSS to ensure that they are side by side. Also, the rows would wrap if there are too many squares in each row or the squares are too wide.