Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial

victor sagrista lopez
1,437 PointsCreate an interactive grid with jQuery
Hi everyone, I'm trying to create a grid with jQuery that has a width of 400px and an automatic height. It should be made of squares that resize based on how many you pick (from a prompt event).
I have tried to looping using "while" but I can't get to resize the squares to fit and adjust to its parent element. I have been hours researching, but I cannot really find an answer. Here's the javascript I've tried.
var number = +prompt("How many squares?"); while (number > 0) {
var squareWidth = 400 / number ; var squareHeight = 400 / number ;
$(document).ready(function(){
$(".container").append("<div></div>");
$("div").css({
"display": "inline-block",
"width": "squareWidth px",
"height": "squareHeight px",
"background-color": "red"
});
});
number = number - 1
}
Any help would be greatly appreciated. This challenge is really tough to me.
2 Answers

Paul Yabsley
46,713 PointsHi Victor
I'm not sure exactly what you are trying to achieve but there are couple of issues with your code above.
- Your number incrementer is outside of the loop
- Each time the loop runs the size of the square in the grid will change because number will be different each time through the loop. Set it outside the loop.
- You need to select the descendent divs of .container otherwise you'll reset the size of that with your css
- Don't think you need document.ready in your loop
- You can use a single variable for the width/height if your shape is going to be square
Try the following. I've added in a border left and bottom so you can see the squares you're adding.
var number = prompt("How many squares?");
var squareSize = 400 / number;
while (number > 0) {
$(".container").append("<div></div>");
$(".container div").css({
"display": "inline-block",
"width": squareSize + "px",
"height": squareSize + "px",
"background-color": "red",
"border-left": "1px solid black",
"border-bottom": "1px solid black",
});
number--;
};

victor sagrista lopez
1,437 PointsGreat points! thank you