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! While you're at it, check out some resources Treehouse students have shared here.

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
victor sagrista lopez
1,437 Points

Create 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 ;


        "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
Paul Yabsley
46,713 Points

Hi Victor

I'm not sure exactly what you are trying to achieve but there are couple of issues with your code above.

  1. Your number incrementer is outside of the loop
  2. 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.
  3. You need to select the descendent divs of .container otherwise you'll reset the size of that with your css
  4. Don't think you need document.ready in your loop
  5. 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 div").css({
      "display": "inline-block",
      "width": squareSize + "px",
      "height": squareSize + "px",
      "background-color": "red",
      "border-left": "1px solid black",
      "border-bottom": "1px solid black",