Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate 3000 squares procedurally

I need to build a widget that contains 3000 squares. Doing this manually would take a very long time, maybe some of you know the easiest way to generate the class .square 3000 times? I need also be able to alter the content of each square, for example a color, title, etc. Thx friends!

<div class="square">
  <h1>10</h1>
</div>

https://jsfiddle.net/srowf8hg/

like image 233
Lukas Avatar asked Dec 22 '25 20:12

Lukas


2 Answers

You just need a loop and create a new square on each iteration. In order to be able to access each square individually, each generated square gets its own unique id:

var cont = document.getElementById("container");

for(var i = 1; i <3001; ++i){
 var div = document.createElement("div");
 div.setAttribute("class", "square");
 div.setAttribute("id", "div" + i);
 
 var h1 = document.createElement("h1");
   h1.textContent = i;
   div.appendChild(h1);
   cont.appendChild(div);
 }
.square{
  background:#fa5339;
  color:#fff;
  width:100px;
  height:100px;
  float:left;
  border:1px solid #d63d26;
}
h1{
    height: 50%; 
    width:100%;
    display:flex;
    align-items: center;
    justify-content: center;
}
<div id=container>
  
</div>
like image 200
Scott Marcus Avatar answered Dec 24 '25 10:12

Scott Marcus


Your question is very vague.

What technologies are you willing ( or able in the case of homework like project) to use to achieve your goal?

If you have no idea how to do it then i would suggest you start learning of some jQuery, that is a javascript framework, that allows you to do some pretty cooll and easy stuff.

If you do end up using jquery, all you would have to do is to create an element lets say:

<div id="container"></div>

and then somewhere in your javascsript you would have a javascript array with the objects that you are rendering for, say an object named square { color,title,text,name,this,that }

And after that you could just create a loop,construct your html elements as string and use jquery to append the elements in your DOM. An example would be :

var myContainer = $('#container'); <--- this holds a reference to the container element using jquery
for(var i=0,len=myArray.length;i<length;i++){ <-- in my array you would have your "square" objects so that you can modify each square based on parameters like name,title,color etc
    var elementInString = '<div class="square" style="color:"'+myArra[i].color+'>';   <-- and create your parameterised square here
    $(myContainer).append(elementInString);
}

This is one way to do it. Other way include using other frameworks (Knockout,Angular etc)

I hope this helps

like image 44
MKougiouris Avatar answered Dec 24 '25 10:12

MKougiouris