JavaScript - create number of divs in loop - javascript

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.

Related

How can I write each character from string to separate div using JavaScript?

This is what I have been far
This is my code:
function createWordTiles() {
var word = ['Example'];
var innerDiv;
var iDiv = document.createElement('div');
iDiv.id = 'tileBlock';
iDiv.className = "tileBlock";
Code works only i remove loop :
for (var l = 0; l <= word.length ; l++) {
innerDiv = document.createElement('div');
innerDiv.id = 'Block' + l;
innerDiv.className = 'Block';
innerDiv.innerHTML = word.charAt(l);
}
iDiv.appendChild(innerDiv);
document.getElementsByTagName('body')[0].appendChild(iDiv);
}
This is what I have made
How can I write each character from string to separate div using JavaScript?
Move your iDiv.appendChild(innerDiv); inside the for loop, like this:
for (var l = 0; l <= word.length ; l++) {
innerDiv = document.createElement('div');
innerDiv.id = 'Block' + l;
innerDiv.className = 'Block';
innerDiv.innerHTML = word.charAt(l);
iDiv.appendChild(innerDiv);
}
HTML
<div class="container">
<p class="source-text">Hello world</p>
</div>
<ul class="list"></ul>
js
jQuery(document).ready(function($) {
var sourceText = $('.source-text').text(); // get the source text
var $destinationElm = $('.list'); // get destination
var i;
for(i = 0; i < sourceText.length; i++) { // eterate through all characters
$destinationElm.append('<li>' + sourceText[i] + '</li>'); // appends html element with text
}});

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>

how to create more elements for the entered value in a textboxes in javascript?

I use for loop to create 3 textboxes with it's ids in javascript.. if I enter numbers on each text box I want to display same number of paragraphs element under each text box..
I have a problem: each textbox affected when i enter value in the other text boxes..
There is my codes:
for (i = 0; i < 3; i++) {
var tx = document.createElement('input');
tx.setAttribute('id', i);
tx.onblur = function () {
for (i = 0; i < 3; i++) {
var no = document.getElementById(i).value;
num = Number(no);
var d = document.getElementById('di' + i);
for (x = 0; x < num; x++) {
var tx1 = document.createElement('p');
tx1.innerHTML = " p" + x;
d.appendChild(tx1);
}
}
};
var div1 = document.createElement('div');
div1.setAttribute('id', "di" + i);
var div = document.getElementById('div1');
div.appendChild(tx);
div.appendChild(div1);
}
There are issues in code.
1)
var div = document.getElementById('div1');
div.appendChild(tx);
The code is asking for div with ID div1 which is never appended to DOM hence it returns null
thus null.appendChild(tx) fails.
Thanks
Added JSFiddle. If this is what you are trying to make..
http://jsfiddle.net/khm63wte/
just change your code, create a div on your document <div id="t"></div>, in your javascript create div first, then your input and append them to the document here is a working code
for (i = 0; i < 3; i++) {
var div1 = document.createElement('div');
div1.setAttribute('id', "di" + i);
document.getElementById('t').appendChild(div1)
var tx = document.createElement('input');
tx.setAttribute('id', i);
document.getElementById("di"+i).appendChild(tx);
tx.onblur = function () {
for (i = 0; i < 3; i++) {
var no = document.getElementById(i).value;
num = Number(no);
var d = document.getElementById('di' + i);
for (x = 0; x < num; x++) {
var tx1 = document.createElement('p');
tx1.innerHTML = " p" + x;
d.appendChild(tx1);
}
}
};
}

Randomly shuffle innerHTML

I'm trying to shuffle som innerHTML, I've created some divisions were I add content from a list, now I want to shuffle this everytime I load the site. I've come up with this solution, and it shuffles the innerHTML, but It doesn't put it out in new HTML. Any ideas how to tweak it? Later I will create and shuffle a list of hrefs of image pictures. So basically it is going to be an 9-square image randomizer. I would really appriciate some help :)
<script>
var squareNumbers = ['1','2','3','4','5','6','7','8','9']; //need to create a new list to append image hrefs
for(var i = 0; i<=squareNumbers.length-1; i++){ //creates the chessboard
var div = document.createElement('div');
div.setAttribute('id', 'square'+squareNumbers[i]);
div.innerHTML = squareNumbers[i];
var checkHTML = document.getElementById('chessBoard').appendChild(div);
}
window.onload = function(){
var squareDivs = document.getElementById('chessBoard').getElementsByTagName('div');
var array = [];
for(var i = 0; i < squareDivs.length; i++){ //creates an array of the squares innerHTML
array.push(squareDivs[i].innerHTML);
}
var i = array.length, j, temp;
while(--i > 0){ //shuffles the array according to Fisher Yeates algorithm
j = Math.floor(Math.random() * (i+1));
temp = array[j];
array[j] = array[i];
array[i] = temp;
var squares = document.getElementById('chessBoard').getElementsByTagName('div').innerHTML = temp;
console.log(squares);
}
}
</script>
Update
This just updates them.
var squareNumbers = ['1','2','3','4','5','6','7','8','9'], j, temp;
for(var i = 0; i < squareNumbers.length; i++){ //creates the chessboard
var div = document.createElement('div');
div.setAttribute('id', 'square' + squareNumbers[i]);
div.innerHTML = squareNumbers[i];
document.getElementById('chessBoard').appendChild(div);
}
window.onload = function(){
for (i = squareNumbers.length - 1; i >= 0; i--) {
j = Math.floor(Math.random() * (i + 1));
temp = squareNumbers[j];
squareNumbers[j] = squareNumbers[i];
squareNumbers[i] = temp;
document.getElementById('chessBoard').getElementsByTagName('div')[i].innerHTML = temp;
}
}
Previous
Here, this does that:
window.onload = function(){
var squareNumbers = ['1','2','3','4','5','6','7','8','9'], j, temp;
for (i = squareNumbers.length - 1; i >= 0; i--) {
j = Math.floor(Math.random() * (i + 1));
temp = squareNumbers[j];
squareNumbers[j] = squareNumbers[i];
squareNumbers[i] = temp;
var div = document.createElement('div');
div.setAttribute('id', 'square'+squareNumbers[i]);
div.innerHTML = squareNumbers[i];
document.getElementById('chessBoard').appendChild(div);
}
}

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