Arun Kumar Mohan
Arun Kumar Mohan

Reputation: 11915

Drawing squares within squares in JS

I am trying to run a script to draw a pattern of squares within squares.

var bodyNode = document.getElementsByTagName("body")[0];
var width = 600, height = 600;
var top = 10, left = 10;

while(width > 30) {
    var divNode = document.createElement("div");
    divNode.style.position = "absolute";
    divNode.style.marginLeft = left;
    divNode.style.marginTop = top;

    divNode.style.width = width;
    divNode.style.height = height;
    divNode.style.background = randomColor();

    bodyNode.appendChild(divNode);

    width -= 10;
    height -= 10;
    top += 10;
    left += 10;

}

function randomColor()
   {
       var color = "#";
       for(var i =0; i < 6; i++)
       {
           var number = Math.floor(Math.random() * 10);
           color += number;
       }
   return color;
  }

But the properties which get added to the div are:

{
    position: absolute;
    margin-left: 260px;
    width: 350px;
    height: 350px;
    background: rgb(88, 88, 5);
}

I am trying to achieve this pattern but I get a different pattern as shown in the image below.

What am I missing?

Current output

Upvotes: 0

Views: 1056

Answers (2)

Atul
Atul

Reputation: 440

you are missing "px" suffix of Top,Left,Width,Height See your corrected code here - https://jsfiddle.net/jw2rohr5/

Your corrected code -

var bodyNode = document.getElementsByTagName("body")[0];
var width = 600, height = 600;
var top = 10, left = 10;
while(width > 30)
{
    var divNode = document.createElement("div");
    divNode.style.position = "absolute";
    divNode.style.marginLeft = left + "px";
    divNode.style.marginTop = top + "px";

    divNode.style.width = width + "px";
    divNode.style.height = height + "px";
    divNode.style.background = randomColor();

    bodyNode.appendChild(divNode);

    width -= 10;
    height -= 10;
    top += 10;
    left += 10;

}



function randomColor()
   {
       var color = "#";
       for(var i =0; i < 6; i++)
       {
           var number = Math.floor(Math.random() * 10);
           color += number;
       }
   return color;
  }

You should give suffix like "%","px" etc..

Upvotes: 3

Mart&#237;n Mtz
Mart&#237;n Mtz

Reputation: 41

Try

body{ position: relative; }

When the content have a position by default(static) the margin of node children not work correctly

Upvotes: 0

Related Questions