abenya
abenya

Reputation: 53

Creating a grid using for loops jquery

I am trying to create a 16x16 grid using jquery. I have a main div, and then I'm trying to create the grid within it. I am using for loops, but when the code below runs, I get a 16x32 grid.

Could anyone explain what is going on and why that is happening?

<html>
<head>
    <title>etch-a-sketch</title>
    <link type="text/css" rel="stylesheet" href="stylesheet.css"/>
</head>
<body>
    <div id=main>
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <script type='text/javascript' src='app.js'></script>
</body>

#main {
   height: 192px;
   width: 192px;
   background-color: antiquewhite;
}

.squares {
   height: 10px;
   width: 10px;
   margin: 1px;
   background-color: aquamarine;
   display: inline-block;
}

$(document).ready(function() {
   for(var x = 0; x < 16; x++) {
       for(var y=0; y<16; y++) {
           $("<div class='squares'></div>").appendTo('#main');
       }
   }
});

Upvotes: 1

Views: 676

Answers (2)

user7528695
user7528695

Reputation:

You get a 16x16 grid. When you're using "inline", spaces take place. Just change the CSS code to this:

#main {
  height: 192px;
  width: 192px;
  background-color: antiquewhite;
}

.squares {
  height: 10px;
  width: 10px;
  margin: 1px;
  background-color: aquamarine;
  display: block;
  float: left;
}

Note:

display: block;
float: left;

Upvotes: 2

oompahlumpa
oompahlumpa

Reputation: 503

I think your thought process was off.. I think the best way to make a 16x16 grid (256 boxes total) would be the way I went below and use css to style them.

The HTML

<div id="main">

</div>

The CSS

#main {
  width: 100%;
}
.squares {
  width:6%;
  height: 50px;
  border: 1px solid red;
  display:inline-block;
}

The Javascript

for(var x = 0; x < 256; x++) {
    $("<div class='squares'>hi</div>").appendTo('#main');
}

Upvotes: 0

Related Questions