Randomly shuffle innerHTML - javascript

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);
}
}

Related

Having issues creating a for loop for a list created in JS

I'm trying to for loop the H1 object through a list 10 times. I'm not sure where I went wrong any help would be appreciated.
var headOne = document.createElement("H1");
headOne.textContent = "Hello World";
document.body.appendChild(headOne);
var newOrderedList = document.createElement('OL');
newOrderedList.setAttribute("id", "OLJS");
document.body.appendChild(newOrderedList);
var helloWorld = document.getElementById("OLJS");
for (var i = 0; headOne < 10; i++){
var listItems = document.createElement("li");
listItems.innerHTML = headOne[i];
helloWorld.append(listItems);
}
If you want to loop 10 times then do:
for (let i = 0; i < 10; i++) {
// Do something
}
And in your case if you are trying to access each letter of headOne element and append it to the helloWorld list then you can do the following:
for (let i = 0; i < headOne.textContent.length; i++) {
let listItems = document.createElement('li')
listItems.textContent = headOne.textContent[i]
helloWorld.append(listItems)
}
You might also want to read more about Loops and iteration
var headOne = document.createElement("H1");
headOne.textContent = "Hello World";
document.body.appendChild(headOne);
var newOrderedList = document.createElement('OL');
newOrderedList.setAttribute("id", "OLJS");
document.body.appendChild(newOrderedList);
//var helloWorld = document.getElementById("OLJS");
for (var i = 0; i < 10; i++) {
var listItems = document.createElement("li");
listItems.innerHTML = "order list item " + (i + 1);
newOrderedList.append(listItems);
}

How to append an array to a div?

So I'm having some trouble getting my array to load into a specified area in my HTML, currently the HTML looks like this:
<body>
<div id="japan"></div>
</body>
<script src="Fisher-Yates.js"></script>
and my Javascript is:
let hiragana = [あ, い, う, え, お];
let result = shuffle(hiragana);
let div = document.getElementById('japan');
for (let i = 0; i < result.length; i++) {
div.appendChild(result[i]);
}
It will appear in the body if I replace the div.appendChild with document.body.appendChild instead, so I think some of the code should work, I'm just not sure what I'm missing!
EDIT: I should also mention that the array is variables that are images I'd like to load in at random, this is the rest of the code:
function shuffle(array) {
var m = array.length,
t,
i;
while (m) {
i = Math.floor(Math.random() * m--);
t = array[m];
array[m] = array[i];
array[i] = t;
}
return array;
}
let あ = document.createElement("img");
あ.src = "/images/あ.png";
//あ.setAttribute("width", "25%");
let い = document.createElement("img");
い.src = "/images/い.png";
let う = document.createElement("img");
う.src = "/images/う.png";
let え = document.createElement("img");
え.src = "/images/え.png";
let お = document.createElement("img");
お.src = "/images/お.png";
Try adding the image elements at the top of the code.
let あ = document.createElement("img");
あ.src = "/images/あ.png";
//あ.setAttribute("width", "25%");
let い = document.createElement("img");
い.src = "/images/い.png";
let う = document.createElement("img");
う.src = "/images/う.png";
let え = document.createElement("img");
え.src = "/images/え.png";
let お = document.createElement("img");
お.src = "/images/お.png";
let hiragana = [あ, い, う, え, お];
let result = shuffle(hiragana);
let div = document.getElementById('japan');
for (let i = 0; i < result.length; i++) {
div.appendChild(result[i]);
}
function shuffle(array) {
var m = array.length,
t,
i;
while (m) {
i = Math.floor(Math.random() * m--);
t = array[m];
array[m] = array[i];
array[i] = t;
}
return array;
}
<body>
<div id="japan"></div>
</body>
<script src="Fisher-Yates.js"></script>
Instead of div.appendChild(result[i]); Have you tried below code:
<body>
<div id="japan"></div>
</body>
<script src="Fisher-Yates.js"></script>
let hiragana = [あ, い, う, え, お];
let result = shuffle(hiragana);
div = document.getElementById('japan');
for (let i = 0; i < result.length; i++) {
div.innerHTML = div.innerHTML + result[i];
}

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.

Replace array elements with onclick

I am trying to display new list of shuffled array on onclick but my code is just appending the new shuffled array below the previous list. My code is:
function shuffleArray() {
var array = ['1','2','3','4'];
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
for (i=0;i<array.length;i++) {
var span = document.createElement('span');
span.innerHTML = array[i];
span.onclick = shuffleArray; //calls the same function
var div = document.createElement('div');
div.appendChild(span);
document.body.appendChild(div);
}
}
Current output:
2
1
4 // if I click here then results gets appended below
3
3
2
4
1 // if I click here then results gets appended below
2
1
4
3 // and so on
Desired output: I want the page content to get updated with new array elements, each time I click some array element.
What follows is the simple version, but this is prone to memory leaks because you are using .onclick and are not removing those references before destroying the elements with .innerHTML='';
var wrapping_div = document.createElement('div');
document.body.appendChild(wrapping_div);
function shuffleArray() {
var array = ['1','2','3','4'];
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
wrapping_div.innerHTML = '';
for (i=0;i<array.length;i++) {
var span = document.createElement('span');
span.innerHTML = array[i];
span.onclick = shuffleArray; //calls the same function
var div = document.createElement('div');
div.appendChild(span);
wrapping_div.appendChild(div);
}
}
shuffleArray();
A better way is http://jsfiddle.net/NCUDv/2/:
var wrapping_div = document.createElement('div');
document.body.appendChild(wrapping_div);
function shuffleArray() {
var i, j, temp, span, div,
c = wrapping_div.childNodes,
l = c.length,
array = ['1','2','3','4'],
k = array.length;
for (i=k-1; i>=0; i--) {
j = Math.floor(Math.random() * (i + 1));
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
for (i=l-1; i>=0; i-- ) {
c[i].firstChild.removeEventListener('click', shuffleArray);
wrapping_div.removeChild(c[i]);
}
for (i=0; i<k; i++) {
span = document.createElement('span');
span.innerHTML = array[i];
span.addEventListener('click', shuffleArray);
div = document.createElement('div');
div.appendChild(span);
wrapping_div.appendChild(div);
}
}
shuffleArray();
var container=document.createElement ("div");
document.body.appendChild (container);
function shuffleArray() {
var array = ['1','2','3','4'], l=array.length;
var i,j,tmp;
for (i = l - 1; i > 0; i--) {
j = Math.floor(Math.random() * (i + 1));
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
var span;
container.innerHTML="";
for (i=0;i<l;i++) {
span = document.createElement('span');
span.innerHTML = array[i];
span.onclick = shuffleArray; //calls the same function
container.appendChild(span);
}
}
edited
var container=document.createElement ("div");
document.body.appendChild (container);
function shuffleArray() {
var array = ['1','2','3','4'], l=array.length;
var i,j,tmp;
for (i = l - 1; i > 0; i--) {
j = Math.floor(Math.random() * (i + 1));
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
var p;
container.innerHTML="";
for (i=0;i<l;i++) {
p = document.createElement('p');
p.style.margin="0px";
p.innerHTML = array[i];
p.onclick = shuffleArray; //calls the same function
container.appendChild(span);
}
}

Categories

Resources