Divs created in Javascript don't appear - javascript

I'm making an rgb guesser game for school, and the stretch goal I'm trying to reach is "making divs in javascript". For some reason, my divs aren't appearing when I'm making them. Here's the javascript code snippers
dothething()
function dothething(){
divs = MakeDivs(4);
var randomcolor = Math.floor(Math.random()*4);
WinningDiv = divs[randomcolor];
}
function MakeDivs(X){
for(i = 0;i<=X;i++){
var div = (document.createElement("div"));
div.style.borderRadius = "50%";
div.height = "100px";
div.width = "125px";
}
console.log(divs)
var container = document.getElementById("container")
container.appendChild(div);
return divs
}
and here's some filler html
<body>
<div> FillerDiv</div>
</body>

You need to include the append inside the loop and use a correct control to append your DIV. Also in case you want to return your DIVs elements, add them to array and return them as in below code:
function MakeDivs(X){
var divs = [];
for(i = 0;i<=X;i++){
var div = (document.createElement("div"));
div.style.borderRadius = "50%";
div.height = "100px";
div.width = "125px";
document.body.appendChild(div);
divs.push(div);
}
console.log(divs)
return divs
}

You have to embed container.appendChild(div); inside the loop. In your original code, you have just appended the last div.
function MakeDivs(X){
var container = document.getElementById("container");
var divs = [];
for(i = 0;i<=X;i++){
var div = (document.createElement("div"));
div.style.borderRadius = "50%";
div.height = "100px";
div.width = "125px";
divs.push(div);
container.appendChild(div);
}
console.log(divs);
return divs;
}

You forgot to append the div to the container.
var div = (document.createElement("div"));
div.style.borderRadius = "50%";
div.height = "100px";
div.width = "125px";
container.appendChild(div);

Missing array of divs.
Incorrect way to apply width and height.
div.height = "100px";
^
div.width = "125px";
^
dothething()
function dothething() {
divs = MakeDivs(4)
var randomcolor = Math.floor(Math.random() * 4)
WinningDiv = divs[randomcolor]
}
function MakeDivs(X) {
var container = document.getElementById("container");
var divs = [];
for (i = 0; i <= X; i++) {
var div = (document.createElement("div"));
div.style.borderRadius = "50%";
div.style.height = "100px";
div.style.width = "125px";
container.appendChild(div);
divs.push(div);
}
//console.log(divs)
return divs
}
#container div {
background-color: lightgreen;
}
<div>
FillerDiv
<div id='container'></div>
</div>

This is helpful for you. Without defining HTML tag ID you are getting Id container. The variable should be defined before use anywhere.
You missed divs array to define. You should add every div in the loop.
dothething()
function dothething(){
var divs = MakeDivs(4)
var randomcolor = Math.floor(Math.random()*4)
WinningDiv = divs[randomcolor]
}
function MakeDivs(X){
var container = document.getElementById("container");
var divs = [];
for(i = 0;i<=X;i++){
var div = document.createElement("div");
div.style.borderRadius = "50%";
div.height = "100px";
div.width = "125px";
div.innerHTML = 'Test'+i;
divs.push(div);
container.appendChild(div);
}
console.log(divs);
return divs
}
<body>
<div id="container"> FillerDiv</div>
</body>

You can use documentFragment for creating a block which contains all the colored divs. I've refactored a little bit your code. You can check the solution on jsfiddle - https://jsfiddle.net/2zcg59sd/ or you can run the snippet here.
dothething()
function dothething(){
var divs = MakeDivs(4) ;
document.getElementById("randomColors").appendChild(divs);
}
function MakeDivs(X){
var docFragment = document.createDocumentFragment();
for(i = 0;i<=X;i++){
var randomcolor = Math.floor(Math.random()*900000) + 100000;
var newDiv = document.createElement("div");
newDiv.style.borderRadius = "50%";
newDiv.style.height = "100px";
newDiv.style.float = "left";
newDiv.style.width = "125px";
newDiv.style.backgroundColor = "#" + randomcolor;
docFragment.appendChild(newDiv);
}
return docFragment
}
<div> FillerDiv</div>
<div id="randomColors"></div>

Related

how to get height of an element using .offsetHeight?

I created a div element
let divContainer = document.createElement("div");
divContainer.style.height = "70%";
divContainer.id = "container";
Then, I am doing something like this...
labels.forEach(label => {
let labelDiv = document.createElement("div");
labelDiv.className = "label";
labelDiv.style.height = divContainer.offsetHeight / labels.length; // here I want to retrieve the length of the divContainer in pixels.
divContainer.appendChild(labelDiv);
});
label is an array.
When I run this code labelDiv.style.height comes out to be 0px.
I was looking for a reason for this behaviour and I found this question Element offsetHeight always "0".
As suggested in one of the answers, I used the following code
requestAnimationFrame(() => {
/* should be able to get offsetHeight here */
console.log(divContainer.offsetHeight);
};
and indeed I got the correct height for the label element inside the requestAnimationFrame but labelDiv.style.height is still 0 in the code given below.
I believe labelDiv.style.height is still being calculated before the code in requestAnimationFrame runs.
let divContainer = document.createElement("div");
divContainer.style.height = "70%";
divContainer.id = "container";
requestAnimationFrame(() => {
/* should be able to get offsetHeight here */
console.log(divContainer.offsetHeight);
});
labels.forEach(label => {
let labelDiv = document.createElement("div");
labelDiv.className = "label";
labelDiv.style.height = divContainer.offsetHeight / labels.length;
divContainer.appendChild(labelDiv);
});
Then. I changed the above code to this but still, I am not getting the correct output. In this case I am not again getting 0px for divContainer.offsetHeight
let divContainer = document.createElement("div");
divContainer.style.height = "70%";
divContainer.id = "container";
requestAnimationFrame(() => {
/* should be able to get offsetHeight here */
console.log(divContainer.offsetHeight);
labels.forEach(label => {
let labelDiv = document.createElement("div");
labelDiv.className = "label";
labelDiv.style.height = divContainer.offsetHeight / labels.length;
divContainer.appendChild(labelDiv);
});
});
What is wrong with the above code? What's the proper way to get the height of that element?
Three things:
you need to give body a height, since by default that's 0 (70% of 0 is 0)
you need to append the container to the body before iterating (70% of no parent is 0)
you need to add a unit to the label heights (right now it's just a number)
let labels = ["A", "B", "C"];
document.body.style.height = "500px";
let divContainer = document.createElement("div");
divContainer.style.height = "70%";
divContainer.style.backgroundColor = "red";
divContainer.id = "container";
document.body.append(divContainer)
labels.forEach(label => {
console.log(divContainer.offsetHeight)
let labelDiv = document.createElement("div");
labelDiv.className = "label";
labelDiv.style.height = divContainer.offsetHeight / labels.length + "px";
labelDiv.style.background = "blue";
divContainer.appendChild(labelDiv);
});
To follow up on my comment.
document.getElementById("app").innerHTML = `
<h1>Label Boxes!</h1>
`;
let labels = ["label1", "label2", "label3", "label4", "label5"];
let divContainer = document.createElement("div");
divContainer.style.height = "70%";
divContainer.style.border = "2px solid palevioletred";
divContainer.id = "container";
document.body.appendChild(divContainer);
requestAnimationFrame(() => {
/* should be able to get offsetHeight here */
console.log(divContainer.getBoundingClientRect().height);
labels.forEach(label => {
let labelDiv = document.createElement("div");
labelDiv.className = "label";
labelDiv.style.height = divContainer.getBoundingClientRect().height / labels.length + "px";
labelDiv.style.border = "1px solid palegreen";
divContainer.appendChild(labelDiv);
});
});
html, body {
height: 100%;
}
<div id="app"></div>

How to correctly use DOM style margin top property in javascript?

I am trying to get my div element to the center of the screen that I have aligned to the center but the top margin is still stuck on the top and not centered.
I have tried divElement.style.marginTop = "100px"; but that didn't change anything.
//this is the javascript
function stopDesc(){
var divElement = document.createElement("Div");
divElement.id = "divID";
// Styling it
divElement.style.textAlign = "center";
divElement.style.fontWeight = "bold";
divElement.style.fontSize = "smaller";
//divElement.style.marginTop = "100px";
divElement.style.paddingTop = "100px";
divElement.style.width = "500px";
divElement.style.height = "250px";
divElement.style.background = "orange";
divElement.style.margin="0 auto";
divElement.style.color = "white";
divElement.style.position="relative";
divElement.style.zIndex="1000";
// Adding a paragraph
var paragraph = document.createElement("P");
var text =
document.createTextNode("Text..................................");
paragraph.appendChild(text);
divElement.appendChild(paragraph);
// Adding a button
var button = document.createElement("Button");
var textForButton = document.createTextNode("Next->");
button.appendChild(textForButton);
button.addEventListener("click", function(){
alert("Hi!");
});
divElement.appendChild(button);
// Appending the div element to body
document.getElementsByTagName("body")[0].appendChild(divElement);
//document.getElementById("divID").setAttribute('align','center');
}
Right now the div is centered but the top is stuck to the top of the screen and I want it in the center or at least 100px down from the top.
Edit this line:
divElement.style.margin="0 auto";
and make it:
divElement.style.margin="100px auto";
maybe you've added divElement.style.marginTop = "100px" above that line of code so that it was overriden.
var divElement = document.createElement("Div");
divElement.id = "divID";
// Styling it
divElement.style.textAlign = "center";
divElement.style.fontWeight = "bold";
divElement.style.fontSize = "smaller";
//divElement.style.marginTop = "100px";
divElement.style.paddingTop = "100px";
divElement.style.width = "500px";
divElement.style.height = "250px";
divElement.style.background = "orange";
divElement.style.margin="100px auto";
divElement.style.color = "white";
divElement.style.position="relative";
divElement.style.zIndex="1000";
// Adding a paragraph
var paragraph = document.createElement("P");
var text =
document.createTextNode("Text..................................");
paragraph.appendChild(text);
divElement.appendChild(paragraph);
// Adding a button
var button = document.createElement("Button");
var textForButton = document.createTextNode("Next->");
button.appendChild(textForButton);
button.addEventListener("click", function(){
alert("Hi!");
});
divElement.appendChild(button);
// Appending the div element to body
document.getElementsByTagName("body")[0].appendChild(divElement);
//document.getElementById("divID").setAttribute('align','center');

Border does not go around full table

I have a border that I'm trying to get to go around the full table, but instead it stops at odd places and does not circle the whole table. Looking like this:
So as you can see the border stops going around the table in an odd place, so how do I get it to fully encompass the table?
Also due to certain specifications the whole thing must be created with Javascript.
function createTable(matrix) {
var div = document.createElement("div");
div.style.minWidth = "120px";
//div.style.height = "100px";
div.style.top = "0px";
div.style.left = "0px";
div.style.zIndex = 1000;
div.style.background = "grey";
div.style.color = "white";
div.style.position = "absolute";
var header = document.createElement("div");
header.style.background = "red";
header.style.textAlign = "center";
header.innerHTML = "Script Stats";
div.appendChild(header)
var x = document.createElement("TABLE");
//x.style.padding = "50px";
for (i = 0; i < matrix.length; i++) {
tableData[i] = [];
tableData[i][0] = document.createElement("TR");
x.appendChild(tableData[i][0]);
for (let k = 0; k < matrix[i].length; k++) {
var z = document.createElement("TD");
z.innerHTML = matrix[i][k];
z.style.textAlign = "center";
z.style.padding = "5px";
tableData[i][0].appendChild(z);
}
}
x.style.border = "2px solid white";
div.appendChild(x);
var bottom = document.createElement("div");
bottom.style.background = "red";
bottom.innerHTML = "Menu";
bottom.style.textAlign = "center";
div.appendChild(bottom);
document.body.appendChild(div);
}
createTable(divTable);
Okay, I reproduced your problem, and
a simple solution to your problem is
<style>
table { border-collapse: collapse; }
</style>
you can see it in action here :
https://jsbin.com/jenupigupe/edit?html,js,output

Remove div's with almost the same id once a certain top value is reached

So I've got this code to create a rectangular div every 800ms which falls down the screen.
Now I'd like to be able to remove a div once it reaches a certain top value, otherwise it'll
get too cluttered with div's. Now I have no idea how to exactly do that, considering the id's I've given them. I'd also like to know how I could end up removing every single one of those div's once it's game over. This is what I have so far all together: http://student.howest.be/pieter-jan.vandenb1/crossdodger/Game.html. I'm pretty new at javascript so thanks in advance!
var idNumber = 0;
SpawnBlock();
function SpawnBlock()
{
UpdateBlock();
setTimeout(SpawnBlock, 800);
}
function UpdateBlock()
{
var block = document.createElement("div");
block.style.width = "25px";
block.style.height = "25px";
block.style.background = "lightgrey"
block.style.top = "-25px";
block.style.left = Math.random() * 455 + "px";
block.style.position = "absolute";
block.id = "block" + ++idNumber;
//block.speed = 0.5;
sym.$("Stage").append(block);
sym.$("#block"+idNumber).transition({top:"800px"},8000,"linear");
}
It's made in Adobe Edge, hence the "sym." namespace.
This worked for me in a similar environment:
var bl = document.getElementById("block" + (idNumber));
bl.parentNode.removeChild(bl);
var idNumber = 0;
SpawnBlock();
var divblocks = [];
function SpawnBlock()
{
UpdateBlock();
setTimeout(SpawnBlock, 800);
}
function UpdateBlock()
{
var block = document.createElement("div");
block.style.width = "25px";
block.style.height = "25px";
block.style.background = "lightgrey"
block.style.top = "-25px";
block.style.left = Math.random() * 455 + "px";
block.style.position = "absolute";
block.id = "block" + ++idNumber;
//block.speed = 0.5;
sym.$("Stage").append(block);
sym.$("#block"+idNumber).transition({top:"800px"},8000,"linear");
divblocks.push(block.id);
if (divblocks.length > 800)
{
$(divblocks[0]).Remove();
}
}

Absolute positioning for dynamically created elements

I am trying to overlay text onto a hyperlinked image which has been dynamically created using the document.createElement() function. However, even with an absolute position of left: 0px and top: 0px, the text keeps appearing below the image, and not at the top, left corner as it should:
//mainDiv is a container to hold all the hyperlinked images
for (i = 0; i < imgArray.length; i++)
{
img = document.createElement("img");
img.src = imgArray[i].src;
img.style.width = imgArray[i].wdth;
img.style.height = "auto";
imgLink = document.createElement("a");
imgLink.href = imgArray[i].url;
imgLink.appendChild(img);
imgLabel = document.createElement("p");
imgLabel.innerHTML = imgArray[i].desc;
imgLabel.style.position = "absolute";
imgLabel.style.top = "0px";
imgLabel.style.left = "0px";
imgContainer = document.createElement("div");
imgContainer.style.display = "inline";
imgContainer.style.position = "relative";
imgContainer.appendChild(imgLabel);
imgContainer.appendChild(imgLink);
mainDiv.appendChild(imgContainer);
}
The only problem is the positioning of the text div, imgLabel.
Here's a simplified example of the issue on jsFiddle: http://jsfiddle.net/mPL3q/1/
block & inline-block does not work: http://jsfiddle.net/MwjXV/
1st solution
// label
imgLabel.style.position = "absolute";
imgLabel.style.top = "0px";
imgLabel.style.left = "0px";
imgLabel.style.margin = '0px';
// container
imgContainer.style.position = "relative";
// tip: parent element of another element containing floated elements
// should have property overflow set to hidden
imgContainer.style.float = "left";
imgContainer.style.margin = "5px";
2nd solution
// label
imgLabel.style.position = "absolute";
imgLabel.style.top = "0px";
imgLabel.style.left = "0px";
imgLabel.style.margin = "0px";
// container
imgContainer.style.display = "inline-block";
imgContainer.style.position = "relative";
// you will have gaps between the containers even if the margin is set to 0
imgContainer.style.margin = "0px";
// if you don't want these gaps, set margin-left to -5px (but not to the first element)
if(i !== 0){
imgContainer.style.marginLeft = "-5px";
}
EDIT After analyzing your code...
// change <p> to <label>
imgLabel = document.createElement("label");
imgLabel.innerHTML = "Image " + i;
imgLabel.style.left = "0px";
// you don't need the next line ;)
//imgLabel.style.top = "0px";
imgLabel.style.color = "White";
imgLabel.style.position = "absolute";
1st jsFiddle | 2nd jsFiddle | 3rd jsFiddle
You can do this, add
img.style.zIndex="1";
and
imgLink.style.display = "block";
to their respective blocks
http://jsfiddle.net/mPL3q/8/
OR
if inline-block works for you then
imgContainer.style.display = "inline-block";
http://jsfiddle.net/mPL3q/7/

Categories