parameters in for loop JavaScript - javascript

I am working on this project for school.
But I cannot figure out one problem.
I have 2 lines of boxed both colored, but I use a for loop and in the parameters don't work in the for loop. The lines have both different places and different length. So how could I use the parameters in the for loop? Just right so it would work everytime.
The code I have so far:
box('box', 3);
box('box2, 4);
function box(id,aantal){
for(var i = 0; i < aantal.length; i++){
var box = document.createElement("div");
box.style.height = "175px";
box.style.width= "175px";
box.style.borderRadius = "5px";
box.style.backgroundColor = "#e6e6e6";
box.style.marginLeft ="25px";
box.style.marginTop = "-160px";
box.style.float = "left";
document.getElementById(id).appendChild(box);
}
}

aantal parameter is a number thus you should not use aantal.length but simply
for (var i = 0; i < aantal; i++) {
box('box', 3);
box('box2', 4);
function box(id, aantal) {
for (var i = 0; i < aantal; i++) {
var box = document.createElement("div");
box.style.height = "175px";
box.style.width = "175px";
box.style.borderRadius = "5px";
box.style.backgroundColor = "#e6e6e6";
box.style.marginLeft = "25px";
box.style.float = "left";
document.getElementById(id).appendChild(box);
}
}
<div id="box"></div>
<div id="box2"></div>

box('box', 3);
box('box2', 4);
function box(id,aantal){
for(var i = 0; i < aantal; i++){
var box = document.createElement("div");
box.style.height = "175px";
box.style.width= "175px";
box.style.borderRadius = "5px";
box.style.backgroundColor = "#e6e6e6";
box.style.marginLeft ="25px";
box.style.marginTop = "-160px";
box.style.float = "left";
document.getElementById(id).appendChild(box);
}
}

From the code below, what I can see is that in the second call to box,
you are not closing the string, which would cause a runtime error. The call should look like this: box('box2', 4);. What is also a problem is that you are expecting aantal to be an array, since you are accessing it's length property. However, you are passing integers as aantal to the function.
box('box', 3);
box('box2, 4);
function box(id, aantal){
for(var i = 0; i < aantal.length; i++){
var box = document.createElement("div");
box.style.height = "175px";
box.style.width= "175px";
box.style.borderRadius = "5px";
box.style.backgroundColor = "#e6e6e6";
box.style.marginLeft ="25px";
box.style.marginTop = "-160px";
box.style.float = "left";
document.getElementById(id).appendChild(box);
}
}
If the function should create a number of boxes, then your loop should look more like for(var i = 0; i < aantal; i++), since aantal is a number itself. Such a loop would then create the number of boxes that you passed in as the second argument.

Related

Can't clone <template> to append to <div>

I create this template successfully with javascript:
I create the template in an async function:
this.createBoxes = async function() {
var row_counter = 0;
for (var i = 1; i < this.fake_data.length + 1; i++) {
var item_box = document.createElement("div");
item_box.style.flex = "0.5";
item_box.style.backgroundColor = "white";
item_box.style.display = "flex";
item_box.style.flexDirection = "column";
item_box.style.justifyContent = "flex-end";
item_box.id = "item_box_"+i;
var item_name = document.createElement("h3");
item_name.style.flex = "0.2";
item_name.style.backgroundColor = "orange";
item_name.style.alignSelf = "center";
item_name.innerText = this.fake_data[i - 1].name;
item_name.id = "item_name_"+i;
item_box.appendChild(item_name);
this_row = document.getElementsByClassName("row")[row_counter];
this_row.appendChild(item_box);
if(i % 2 == 0) {
var pool = document.getElementById("pool");
var inner_row = document.createElement("div");
inner_row.style.display = "flex";
inner_row.style.flexDirection = "row";
inner_row.style.flex = "0.5";
inner_row.style.justifyContent = "space-around";
inner_row.style.alignItems = "center";
inner_row.style.backgroundColor = "green";
inner_row.className = "row";
pool.appendChild(inner_row);
row_counter++;
}
else if(i == this.fake_data.length) {
return;
}
}
}
Then I do this:
this.createBoxes().then(function() {
var template = document.querySelector('#pool');
var clone = template.content.cloneNode(true);
document.querySelector(".app").appendChild(clone);
})
But as you can see from my screenshot, .app is empty. What am I doing wrong? I am using Cordova and I am assuming that it is able to use the template tag, I haven't been able to find anything saying I can't.
UPDATE
This happens:
When I do this:
this.createBoxes().then(function() {
var template = document.querySelector('#pool');
var clone = template.cloneNode(true);
document.querySelector(".app").appendChild(clone);
});
Using template.cloneNode successfully moves the <template> but this is obviously not what I want, I want to get the contents of the <template> and move them to .app container, not the whole <template>.
You should be cloning the template's .content instead, as demonstrated in the documentation.
var temp = document.getElementsByTagName("template")[0];
var clon = temp.content.cloneNode(true);
document.body.appendChild(clon);
Well, if cloning the node itself works, then the answer is pretty simple - just clone/append children of the template:
this.createBoxes().then(function() {
let template = document.querySelector('#pool');
let app = document.querySelector(".app");
for(let child of template.childNodes) {
let clone = child.cloneNode(true);
app.appendChild(clone);
}
});
Note that I have not tested this code - you may need to debug it as necessary.
I added a container to the template programmatically:
var pool = document.getElementById("pool");
var container = document.createElement("div");
container.style.flex = "1";
container.style.backgroundColor = "white";
container.style.display = "flex";
container.style.flexDirection = "column";
container.id = "container";
var row = document.createElement("div");
row.style.display = "flex";
row.style.flexDirection = "row";
row.style.flex = "0.5";
row.style.justifyContent = "space-around";
row.style.alignItems = "center";
row.style.backgroundColor = "green";
row.className = "row";
container.appendChild(row);
pool.appendChild(container);
Then instead of adding my content to the #pool <template>, I added it to #container, and then stored the #container node in a variable, and then imported that into .app:
var container_in_temp = document.querySelector('#pool>#container');
var targetContainer = document.querySelector('.app');
targetContainer.appendChild(document.importNode(container_in_temp, true));
So it ends up looking like this, with a container in .app which is actually kind of preferable structure wise :).

How to change content of first Child dynamic

for(let i = 0; i < 8; i++) {
let childDiv = document.createElement('div');
divi.id = "addDay";
childDiv.className = "boxName";
divi.appendChild(childDiv);
childDiv.textContent = "0";
}
document.querySelector('#map');
map.appendChild(divi);
divi.firstChild.style.backgroundColor = "green";
change();
}
function change(){
n = document.getElementById('addDay');
n.firstChild.textContent = 'something';
}
I need to change content of first child of addDay on every click,but this function makes it only once. What do you think where is problem?

JavaScript: How Can I Make A Var "Array" Work?

Is there a way to name a var using a sort of "Array?" My code is this:
for(var i = 0; i < (getHorizontalSquares * getVerticalSquares); i++){
var Square[i] = document.createElement("div");
Square[i].style.position = "relative";
Square[i].style.float = "left";
Square[i].style.width = "50px";
Square[i].style.height = "50px";
Square[i].id = "square" + (i + 1);
for(var ii = 0; ii < 6; ii++){
var TestColor = TestColorArray[Math.round(Math.random()*(TestColorArray.length - 1))];
getTestColor += TestColor;
}
Square[i].style.backgroundColor = "#" + getTestColor;
SquareCont.appendChild(Square[i]);
}
I know my code doesn't work, but I want to implement the same idea so I can get a result of this:
var Square1...
var Square2...
var Square3...
var Square4...
var Square5...
etc
I also tried doing a "Concentration" var, but it didn't work. How do I do this so the document doesn't append the same square multiple times?
var Square = {};
var SquareCont = document.createElement('div');
var getHorizontalSquares = 10;
var getVerticalSquares = 10;
var TestColorArray = ['a','b','c','f','e','0','1','2','3','3','4','5'];
var getTestColor = '';
for(var i = 0; i < (getHorizontalSquares * getVerticalSquares); i++){
Square['Square'+i] = document.createElement("div");
Square['Square'+i].style.position = "relative";
Square['Square'+i].style.float = "left";
Square['Square'+i].style.width = "50px";
Square['Square'+i].style.height = "50px";
Square['Square'+i].id = "square" + (i + 1);
for(var ii = 0; ii < 6; ii++){
var TestColor = TestColorArray[Math.round(Math.random()*(TestColorArray.length - 1))];
getTestColor += TestColor;
}
Square['Square'+i].style.backgroundColor = "#" + getTestColor;
SquareCont.appendChild(Square['Square'+i]);
getTestColor = '';
}
console.log(Square);
This example does what you want using an object instead of an array, but meets your desire to dynamically create accessible Square1, Square2, etc... They are all contained in Square. In the console with this snippet, you will see that 100 squares are created and added to the Square object. They will be accessible by Square.SquareX (where X is some number), or Square['SquareX'], or Square['Square'+X] where X is some number again.
Your declaration syntax is not valid. But, I think the larger point you are trying to get to is to be able to populate an array with dynamically created elements and that you can do:
var squares = []; // Array must exist before you can populate it
var testColorArray = ["green", "yellow", "blue", "orange", "silver"];
var getTestColor = null;
function makeSquares(count){
for(var i = 0; i < count; i++){
// Just create the element and configure it. No need to worry about the array yet
var element = document.createElement("div");
element.style.float = "left";
element.style.width = "75px";
element.style.height = "75px";
element.id = "square" + (i + 1);
element.style.backgroundColor = testColorArray[Math.floor(Math.random()* testColorArray.length)];
element.textContent = element.id;
squareCont.appendChild(element);
// Now, add the element to the arrray
squares.push(element);
}
// Test:
console.log(squares);
}
makeSquares(10);
<div id="squareCont"></div>

JavaScript - create number of divs in loop

I'm a begginer with javaScript. and I want to create number of windows (div) with loop operation only with javaScript.
This is my code:
var numOfWindows = 3;
var arrayDiv = new Array();
for (var i = 0; i < numOfWindows; i++)
{
arrayDiv[i] = document.createElement('div');
arrayDiv[i].id = 'block' + i;
arrayDiv[i].style.backgroundColor = 'green';
arrayDiv[i].className = 'block' + i;
document.body.appendChild(arrayDiv[i]);
}
but I see a blank screen.
Your JavaScript works perfectly, if you give the created elements some content, or specific dimensions in CSS:
var numOfWindows = 3;
var arrayDiv = new Array();
for (var i = 0; i < numOfWindows; i++)
{
arrayDiv[i] = document.createElement('div');
arrayDiv[i].id = 'block' + i;
arrayDiv[i].style.backgroundColor = 'green';
arrayDiv[i].className = 'block' + i;
// setting the textContent to the 'i' variable:
arrayDiv[i].textContent = i;
document.body.appendChild(arrayDiv[i]);
}
JS Fiddle demo.
Or:
var numOfWindows = 3;
var arrayDiv = new Array();
for (var i = 0; i < numOfWindows; i++) {
arrayDiv[i] = document.createElement('div');
arrayDiv[i].id = 'block' + i;
arrayDiv[i].style.backgroundColor = 'green';
arrayDiv[i].className = 'block' + i;
// setting the class-name of the created elements:
arrayDiv[i].className = 'bordered';
document.body.appendChild(arrayDiv[i]);
}
JS Fiddle demo.
Give your div a specified width and height.
div.style.width = '10px';
div.style.heigt = '10px';
Or give it content.

Javascript - accessing array in an array

So I have this code:
function make_buttons (id) {
var operators = [["*","multiply"],["/","divide"],["+","add"],["-","divide"],["=","calc_it"]]
var parent = document.getElementById(id);
var input = document.createElement("input");
input.type = 'text'; input.id = 'inp';
parent.appendChild(input);
for (var i = 0;i < 10; i++){
var btn = document.createElement ("button");
btn.innerHTML = i;
btn.id = i;
parent.appendChild(btn);
(function(index) {btn.onclick = function() {input.value += index;}})(i);
}
for (var j = 0; j < operators.length; j++) {
var operators[j][1] = document.createElement ("button");
};
So I have an array wich has array inside of it. Now I want to set the name of the variable to be operator name inside of the array. In current case it should be 'multiply'.
But it gives me a syntax error when doing this.
What I want to achieve is this :
var multiply = document.createElement ("button");
multiply.innerHTML = "*";
multiply.id = "*";
parent.appendChild(multiply);
multiply.onclick = function () {input.value += '*';};
var divide = document.createElement ("button");
divide.innerHTML = "/";
divide.id = "/";
parent.appendChild(divide);
var add = document.createElement ("button");
add.innerHTML = "+";
add.id = "+";
parent.appendChild(add);
var substract = document.createElement ("button");
substract.innerHTML = "-";
substract.id = "-";
parent.appendChild(substract);
But with the array, so that there is less code written and also less repetitiveness.

Categories

Resources