user3765383
user3765383

Reputation: 23

Creating <div> grid with JQuery for loop

I'm new to web development but have a pretty solid programming background. I've tried multiple ways to create a element programatically based on user input. I'm trying to essentially create a grid through JQuery.

I'm tackling this problem by storing the user input into a variable and going through a for loop to create the grid. Here is the code for the .js file:

var rows = 8;
var columns = 8;
var $row = $("<div />", {class: 'row'});
var $square = $("<div />", {class: 'square'});

$(document).ready(function(){
    for(var i = 0; i < rows; i++){      
            $("#wrapper").append($row);
    }

    for(var i = 0; i < columns; i++){
            $(".row").append($square);
    }
});

Now for some reason, this code only creates one row in #wrapper and one square in the row. I've tried copying the example CSS files that tackle this problem but nothing seems to work. Here's what I have right now for my CSS:

#wrapper {
    width: 850px;
    height: 850px;

    margin-top: 100px;
    margin-left: auto;
    margin-right: auto;

    background: #000000;
}

.row {
    width: auto;
    height: 100px;

    background: #313131;
}

.square {
    width: 100px;
    height: 100px;

    margin: 0px;

    outline: 1px solid;
    display: inline-block;
    float: left;
    background: #FFFFFF;
}

And here's my HTML:

<!doctype html>
<html>

<head>
    <title>Draw Grid</title>
    <link rel="stylesheet" type="text/css" href="theme.css" >
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>        
    <script src="draw.js"></script>
</head>

<body>

    <div id="wrapper">

    </div>
</body>

</html>

Can anybody help me out? I'm so confused. I've tried everything. Is this a CSS formatting error?

Upvotes: 1

Views: 11731

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

The problem is you are creating only one row and square objects, you need to use cloned copies else they are just copy

var rows = 8;
var columns = 8;
var $row = $("<div />", {
    class: 'row'
});
var $square = $("<div />", {
    class: 'square'
});

$(document).ready(function () {
    //add columns to the the temp row object
    for (var i = 0; i < columns; i++) {
        $row.append($square.clone());
    }
    //clone the temp row object with the columns to the wrapper
    for (var i = 0; i < rows; i++) {
        $("#wrapper").append($row.clone());
    }
});

Demo: Fiddle

Upvotes: 5

Related Questions