Replace array elements with onclick - javascript

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

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

.innerHTML edits HTML but doesnt display

so I have a bit of code that generates a few spans for display of a few range inputs but when the span is edited it shows as if it were edited in the console but not the page
for (var i = 0; i < 5; i++) {
text = document.createElement('span')
span[pos][i] = text;
console.log(text)
div.innerHTML += list[i]
text.setAttribute("id",`${pos}0${i}`)
div.appendChild(text);
div.appendChild(space);
}
div.appendChild(document.createElement('p'))
for (var i = 0; i < 5; i++) {
space = document.createElement('span')
space.setAttribute("style","padding-left: 40px")
slider = document.createElement('input')
range[pos][i] = slider;
slider.setAttribute("type","range")
slider.setAttribute("id",`${pos}1${i}`)
div.appendChild(slider);
div.appendChild(space);
console.log(div, i)
}
for (var i = range.length - 1; i >= 0; i--) {
for (var j=0; j<5; j++) {
span[i][j].innerHTML = range[i][j].value;
//console.log(j)
}
}
I don't understand what you are going to do with the 5 sliders?
var range = [];
var span = [];
function init() {
var div = document.createElement('div');
for (var i = 0; i < 5; i++) {
var text = document.createElement('span');
span[i] = text;
console.log(text);
//div.innerHTML += list[i]
text.setAttribute("id",`txt0${i}`);
div.appendChild(text);
var space = document.createElement('span');
div.appendChild(space);
}
div.appendChild(document.createElement('p'))
for (var i = 0; i < 5; i++) {
var space = document.createElement('span');
space.setAttribute("style","padding-left: 40px");
var slider = document.createElement('input');
range[i] = slider;
slider.setAttribute("type","range");
slider.setAttribute("id",`slider1${i}`);
div.appendChild(slider);
div.appendChild(space);
console.log(div, i)
}
for (var i = range.length - 1; i >= 0; i--) {
for (var j=0; j<5; j++) {
span[i].innerHTML = range[i].value;
//console.log(j);
}
}
document.body.appendChild(div);
}
<body onload="init()">
</body>

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

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

Categories

Resources