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

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>

Related

Trying to export canvas size as file name in Photoshop JSX script

I'm not a programmer, but trying to write a script for Photoshop. Below is something that I found, but it simply increments the files "1.png, 2.png, etc..." I'd like to name the exported files, "documentName_canvasWidth_canvasHeight_incrementedNumber.png"
function sfwPNG24(saveFile){
var pngOpts = new ExportOptionsSaveForWeb;
pngOpts.format = SaveDocumentType.PNG
pngOpts.PNG8 = false;
pngOpts.transparency = true;
pngOpts.interlaced = false;
pngOpts.quality = 100;
activeDocument.exportDocument(new File(saveFile),ExportType.SAVEFORWEB,pngOpts);
}
/*
Incrementing a number inside a text layer then Saving it in PNG
*/
var layer = activeDocument.layers[0];
if (layer.kind == 'LayerKind.TEXT') {
for (var i=1; i < 7; i++) {
layer.textItem.contents = i.toString();
sfwPNG24( 'filepathgoeshere'+ i +'.png');
};
};
Add these changes to the second part of the code:
var layer = activeDocument.layers[0];
// documentName_canvasWidth_canvasHeight_incrementedNumber.png
var srcDoc = app.activeDocument;
// get width and height
var W = srcDoc.width.value;
var H = srcDoc.height.value;
// get document name
var fn = srcDoc.name;
if (layer.kind == 'LayerKind.TEXT')
{
for (var i=1; i < 7; i++)
{
layer.textItem.contents = i.toString();
sfwPNG24( 'filepathgoeshere'+ W + "_" + H + "_" + i +'.png')
}
}

Looping through a set of <p>'s one at a time

I'm trying to figure out how to count the number of p's so every time the button is pressed, it outputs to 0 to 1 until the maximum number of p's is counted.
var big_number = 999999;
var i;
var a = document.getElementsByTagName("p");
function function0() {
for (i=0; i < big_number; i++) {
document.getElementsByTagName("p")[i].innerHTML="text";
}
}
I want it to write to another p every time the button is pressed.
document.getElementsByTagName("p").length // number of p elements on the page
Is that what you were asking?
Make a generic tag adder function then call it:
function addTags(tagName,start, max, container) {
var i = start;
for (i; i < max; i++) {
var newp = document.createElement(tagName);
newp.innerHTML = "paragraph" + i;
container.appendChild(newp);
}
}
var tag = 'p';
var big_number = 30;
var i;
var a = document.getElementsByTagName(tag );
// **THIS is your specific question answer**:
var pCount = a.length;
var parent = document.getElementById('mydiv');
addTags(tag,pCount , big_number, parent);
// add 10 more
a = document.getElementsByTagName(tag );
pCount = a.length;
big_number = big_number+10;
addTags(tag,pCount , big_number, parent);
EDIT:
NOTE: THIS might be better, only hitting the DOM once, up to you to determine need:
function addTagGroup(tagName, start, max, container) {
var tempContainer = document.createDocumentFragment();
var i = start;
for (i; i < max; i++) {
var el = document.createElement(tagName);
el.textContent = "Paragraph" + i;
tempContainer.appendChild(el);
}
container.appendChild(tempContainer);
}
To find out how many <p> elements there are in the document you should use DOM's length property as below :-
var numP = document.getElementsByTagName("P").length;
or
var div = document.getElementById("myDIV");
var numP = div.getElementsByTagName("P").length;
To get number of element inside a tag.

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.

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