Using a for loop to set background images using Javascript - javascript

I am trying to set background URL of all the tiles to the name in the memory array.
I have tried:
document.getElementById('tile_' + i).style.background = 'url(' + memory_array[i] + ') no-repeat';;
But this does not work!
I wasn't sure what to put the arrays names as ... I think url(img.gif) is correct?
var memory_array = ['url(img1.gif)', 'img1.gif', 'img2.gif', 'img2.gif', 'img3.gif', 'img3.gif', 'img4.gif', 'img4.gif', 'img5', 'img5'];
var memory_values = [];
var memory_tile_ids = [];
var tiles_flipped = 0;
Array.prototype.memory_tile_shuffle = function() {
var i = this.length,
j, temp;
while (--i > 0) {
j = Math.floor(Math.random() * (i + 1));
temp = this[j];
this[j] = this[i];
this[i] = temp;
}
}
function newBoard() {
tiles_flipped = 0;
var output = '';
memory_array.memory_tile_shuffle();
for (var i = 0; i < memory_array.length; i++) {
output += '<div id="tile_' + i + '" onclick="memoryFlipTile(this,\'' + memory_array[i] + '\')"></div>';
}
document.getElementById('memory_board').innerHTML = output;
// This is the relevant line
document.getElementById('tile_' + i).style.background = 'url(' + memory_array[i] + ') no-repeat';
}
function memoryFlipTile(tile, val) {
if (tile.innerHTML == "" && memory_values.length < 2) {
tile.style.background = 'url(qm.gif) no-repeat';
tile.innerHTML = val;
if (memory_values.length == 0) {
memory_values.push(val);
memory_tile_ids.push(tile.id);
} else if (memory_values.length == 1) {
memory_values.push(val);
memory_tile_ids.push(tile.id);
if (memory_values[0] == 1) {
tiles_flipped += 2;
//Clear both arrays
memory_values = [];
memory_tile_ids = [];
// Check to see if the whole board is cleared
if (tiles_flipped == memory_array.length) {
alert("Well done your a smart person ... Can you do it again ?");
document.getElementById('memory_board').innerHTML = "";
newBoard();
}
} else {
function flip2back() {
//Flip the 2 tiles back over
var tile_1 = document.getElementById(memory_tile_ids[0]);
var tile_2 = document.getElementById(memory_tile_ids[1]);
tile_1.style.background = 'url(qm.gif) no-repeat';
tile_1.innerHTML = "";
tile_2.style.background = 'url(qm.gif) no-repeat';
tile_2.innerHTML = "";
// Clear both array
memory_values = [];
memory_tile_ids = [];
}
setTimeout(flip2back, 700);
}
}
}
}
div#memory_board {
background: black;
border: 1px solid black;
width: 900px;
height: 540px;
padding: 24px;
margin: 0px auto;
margin-bottom: 10px;
}
div#memory_board > div {
background: url(qm.gif) no-repeat;
background-size: 100% 100%;
border: 1px solid #fff;
width: 120px;
height: 120px;
float: left;
margin: 8px;
padding: 20px;
font-size: 20px;
cursor: pointer;
text-align: center;
color: white;
border-radius: 5px;
}
<!DOCTYPE html>
<html>
<head>
<title>Basic Java</title>
<link href='style.css' type='text/css' rel='stylesheet' />
<script src="java.js"></script>
</head>
<body>
<!--HEADER-->
<div class='holder header'>
<h1>Simple picture guessing game</h1>
</div>
<!--Container-->
<div id='memory_board'>
<script>
newBoard();
</script>
<!--Add window.addEventListener() for window load.-->
</div>
<!--footer-->
<div class='holder footer'>
</div>
</body>
</html>

// This is the relevant line
That line should be
document.getElementById('tile_' + i).style.background = 'url(' + memory_array[i] + ') no-repeat';
And your array should be
var memory_array = ['img1.gif', 'img1.gif', 'img2.gif', 'img2.gif', 'img3.gif', 'img3.gif', 'img4.gif', 'img4.gif', 'img5.gif', 'img5.gif'];
Also make sure the path to your images is correct
Alternatively you can use backgroundImage
document.getElementById('tile_' + i).style.backgroundImage = 'url(' + memory_array[i] + ')';

Few things here
you might consider changing the code at newBoard function as the following
function newBoard() {
tiles_flipped = 0;
var output = '';
memory_array.memory_tile_shuffle();
for (var i = 0; i < memory_array.length; i++) {
output += '<div id="tile_' + i + '" onclick="memoryFlipTile(this,\'' + memory_array[i] + '\')"></div>';
}
document.getElementById('memory_board').innerHTML = output;
// This is the relevant line
var title=document.getElementById('tile_' + i);
var imageUrl=url(memory_array[i] + 'no-repeat');
title.style.backgroundImage = imageUrl;
}
Always store your dom search into a variable and then operate on the variable.
ex: var title=document.getElementById('tile_' + i);
Hope this helps

Related

Forcing a click where i want

Run my snippet code before you read my question and click on some cells, so you can understand my question better!!
I got Player A = vertical and Player B = horizontal, As you can see, Each click gives turns between each player, moving the green background around some cells, how i can force the players only to be able to click the cells that have green behind them?
note: i tried using $(selector).trigger('click'); (JQuery)
var isCol = 0;
var CellPoint = 0;
var board = [];
var P1 = {
points: 0
};
var P2 = {
points: 0
};
for (r = 0; r < 7; r++) {
var line = [];
for (c = 0; c < 7; c++) {
line.push(RandomGenerator(50, 500));
}
board.push(line);
}
function prs(curr, c, r) {
CellPoint = parseInt($(curr).text());
showTable(curr, c, r);
isCol = (isCol + 1) % 2;
clr = isCol ? 'blue' : 'red';
$(curr).text('S');
$('#turn').css("color", clr)
.text(`Player ${(isCol+1)} turn`);
if (CellPoint) {
if (isCol) {
P1.points += CellPoint;
} else {
P2.points += CellPoint;
}
$('#p1').text(`Player 1: ${P1.points}`);
$('#p2').text(`Player 2: ${P2.points}`);
} else {
console.log('selected S');
}
}
function toColor(col, row, chosen_col, chosen_row) {
var ret = false;
switch (isCol) {
case 0:
if (row == chosen_row) {
ret = true;
}
break;
case 1:
if (col == chosen_col) {
ret = true;
}
break;
}
return ret;
}
function showTable(c, chosen_col, chosen_row) {
if(c!==-1){board[chosen_row][chosen_col] = 'S';}
var str = "";
str += "<table border=1>";
for (row = 0; row < 7; row++) {
str += "<tr>";
for (let col = 0; col < 7; col++) {
str += "<td onclick='prs(this, " + col + "," + row + ")'";
if(board[row][col]=='S'){
str += " class=uniqueCell";
} else{
if (toColor(col, row, chosen_col, chosen_row)) {
str += " class='grn' ";} }
str += ">";
if(board[row][col]=='S') {
str += 'S';
} else str += board[row][col];
str += "</td>";
}
str += "</tr>";
}
str += "</table>";
document.getElementById("ff").innerHTML = str;
}
function RandomGenerator(min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
showTable(-1);
var getUnique = function() {
var tdElements = document.querySelectorAll('#ff td');
tdElements[
RandomGenerator(0, tdElements.length)
].classList.add('uniqueCell');
// update the text of the cell using the class
document.querySelector('.uniqueCell').textContent = 'S';
};
getUnique();
td {
border: 2px solid black;
width: 10px;
height: 10px;
text-align: center;
}
td:hover {
background-color: lightgreen;
}
.grn {
background-color: green;
color: white;
}
.turn1 {
background-color: green;
color: red;
}
.turn0 {
background-color: green;
color: blue;
}
.uniqueCell {
background-color: tomato;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div><span id='p1' style='color:red;'>Player1: </span> X <span style='color:blue;' id='p2'>Player2: </span></div>
<p id='turn'>Player 1 turn</p>
<div id="ff"></div>
I would suggest to use pointer-events. I have added JavaScript logic as well as modified CSS little bit.
in JavaScript I am checking for class .grn, if its available then allowing click everywhere. But if .grn is available then only td with .grn class will be clickable.
See below JavaScript logic.
if(document.querySelectorAll(".grn").length>0){
document.getElementById("tbl").classList.add("preventclick");
}else{
document.getElementById("tbl").classList.remove("preventclick");
}
See the Snippet below:
var isCol = 0;
var CellPoint = 0;
var board = [];
var P1 = {
points: 0
};
var P2 = {
points: 0
};
for (r = 0; r < 7; r++) {
var line = [];
for (c = 0; c < 7; c++) {
line.push(RandomGenerator(50, 500));
}
board.push(line);
}
function prs(curr, c, r) {
CellPoint = parseInt($(curr).text());
showTable(curr, c, r);
isCol = (isCol + 1) % 2;
clr = isCol ? 'blue' : 'red';
$(curr).text('S');
$('#turn').css("color", clr)
.text(`Player ${(isCol+1)} turn`);
if (CellPoint) {
if (isCol) {
P1.points += CellPoint;
} else {
P2.points += CellPoint;
}
$('#p1').text(`Player 1: ${P1.points}`);
$('#p2').text(`Player 2: ${P2.points}`);
} else {
console.log('selected S');
}
}
function toColor(col, row, chosen_col, chosen_row) {
var ret = false;
switch (isCol) {
case 0:
if (row == chosen_row) {
ret = true;
}
break;
case 1:
if (col == chosen_col) {
ret = true;
}
break;
}
return ret;
}
function showTable(c, chosen_col, chosen_row) {
if(c!==-1){board[chosen_row][chosen_col] = 'S';}
var str = "";
str += "<table id='tbl' border=1>";
for (row = 0; row < 7; row++) {
str += "<tr>";
for (let col = 0; col < 7; col++) {
str += "<td onclick='prs(this, " + col + "," + row + ")'";
if(board[row][col]=='S'){
str += " class=uniqueCell";
} else{
if (toColor(col, row, chosen_col, chosen_row)) {
str += " class='grn' ";
}
}
str += ">";
if(board[row][col]=='S') {
str += 'S';
} else str += board[row][col];
str += "</td>";
}
str += "</tr>";
}
str += "</table>";
document.getElementById("ff").innerHTML = str;
if(document.querySelectorAll(".grn").length>0 || document.querySelectorAll(".uniqueCell").length > 1){
document.getElementById("tbl").classList.add("preventclick");
}
}
function RandomGenerator(min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
showTable(-1);
var getUnique = function() {
var tdElements = document.querySelectorAll('#ff td');
tdElements[
RandomGenerator(0, tdElements.length)
].classList.add('uniqueCell');
// update the text of the cell using the class
document.querySelector('.uniqueCell').textContent = 'S';
};
getUnique();
table#tbl.preventclick td{
pointer-events: none;
}
td {
border: 2px solid black;
width: 10px;
height: 10px;
text-align: center;
}
td:hover {
background-color: lightgreen;
}
.grn {
background-color: green;
color: white;
}
table#tbl.preventclick td.grn{
pointer-events: auto;
}
.turn1 {
background-color: green;
color: red;
}
.turn0 {
background-color: green;
color: blue;
}
.uniqueCell {
background-color: tomato;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div><span id='p1' style='color:red;'>Player1: </span> X <span style='color:blue;' id='p2'>Player2: </span></div>
<p id='turn'>Player 1 turn</p>
<div id="ff"></div>
Update:
I have added || document.querySelectorAll(".uniqueCell").length > 1 in if condition document.querySelectorAll(".grn").length>0 to fix issue mentioned in comment : there's little problem, try clicking on all the cells, in some cases, where there is no selectable numbers, i can click on anywhere on the S cells

image url shown where image should be

I have a board game and when the user clicks on one of the boxes, it flips over and shows the letter. I wanted to instead have an image displayed when the user clicks instead of a letter. I have an array that holds all of the letters but when replaced with a imageurl, it just shows the url instead of the image. I will paste the html,css and js down below.
js
var memory_array = ["./naruto.gif ", "A", "B", "B", "C", "C", "D", "D"];
var memory_values = [];
var memory_tile_ids = [];
var tiles_flipped = 0;
Array.prototype.memory_tile_shuffle = function() {
var i = this.length,
j,
temp;
while (--i > 0) {
j = Math.floor(Math.random() * (i + 1));
temp = this[j];
this[j] = this[i];
this[i] = temp;
}
};
function newBoard() {
tiles_flipped = 0;
var output = "";
memory_array.memory_tile_shuffle();
for (var i = 0; i < memory_array.length; i++) {
output +=
'<div id="tile_' +
i +
'" onclick="memoryFlipTile(this,\'' +
memory_array[i] +
"')\"></div>";
}
document.getElementById("memory_board").innerHTML = output;
}
function memoryFlipTile(tile, val) {
//if the title is empty and array = 0 then the rest of code will perform
if (tile.innerHTML == "" && memory_values.length < 2) {
//the tile selected will have a white background and the val will be produced
tile.style.background = "#FFF";
tile.innerHTML = val;
//if the array equal = 0
if (memory_values.length == 0) {
//push the val and the title id to their respective arrays
memory_values.push(val);
memory_tile_ids.push(tile.id);
//if the array equal = 1
} else if (memory_values.length == 1) {
//push the val and the title id to their respective arrays
memory_values.push(val);
memory_tile_ids.push(tile.id);
//if memory_values values are the same
if (memory_values[0] == memory_values[1]) {
tiles_flipped += 2;
// Clear both arrays
memory_values = [];
memory_tile_ids = [];
// Check to see if the whole board is cleared
if (tiles_flipped == memory_array.length) {
alert("Board cleared... generating new board");
document.getElementById("memory_board").innerHTML = "";
newBoard();
}
} else {
// if the two flip tiles aren't of the same value
function flip2Back() {
// Flip the 2 tiles back over
var tile_1 = document.getElementById(memory_tile_ids[0]);
var tile_2 = document.getElementById(memory_tile_ids[1]);
tile_1.style.background = "orangered";
tile_1.innerHTML = "";
tile_2.style.background = "orangered";
tile_2.innerHTML = "";
// Clear both arrays
memory_values = [];
memory_tile_ids = [];
}
setTimeout(flip2Back, 700);
}
}
}
}
html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script src="app.js"></script>
</head>
<body>
<div id="memory_board"> </div>
<script>
newBoard();
</script>
</body>
</html>
CSS
<style>
div#memory_board {
background: #CCC;
border: #999 1px solid;
width: 800px;
height: 540px;
padding: 24px;
margin: 0px auto;
}
div#memory_board>div {
background: orangered;
border: #000 1px solid;
width: 71px;
height: 71px;
float: left;
margin: 10px;
padding: 20px;
font-size: 64px;
cursor: pointer;
text-align: center;
}
</style>
You can create new image and set the src value from the array of image. Also set the width and height.
var img= new Image();
img.src = val;
img.width="50";
img.height="50";
tile.appendChild(img);
See the snippet below:
div#memory_board {
background: #CCC;
border: #999 1px solid;
width: 800px;
height: 540px;
padding: 24px;
margin: 0px auto;
}
div#memory_board>div {
background: orangered;
border: #000 1px solid;
width: 71px;
height: 71px;
float: left;
margin: 10px;
padding: 20px;
font-size: 64px;
cursor: pointer;
text-align: center;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="memory_board"> </div>
<script>
var memory_array = ["http://www.clker.com/cliparts/b/6/1/0/124223379411527084631_Train_(1967-1979).svg.med.png", "http://www.clker.com/cliparts/b/6/1/0/124223379411527084631_Train_(1967-1979).svg.med.png", "http://www.clker.com/cliparts/Y/y/T/n/Z/Q/number-2-md.png", "http://www.clker.com/cliparts/Y/y/T/n/Z/Q/number-2-md.png", "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQo95Lf_9XG0mf3Tb_lfMDUDXiywIdpiiCb5jUSTyOi5ACJXa3C6w", "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQo95Lf_9XG0mf3Tb_lfMDUDXiywIdpiiCb5jUSTyOi5ACJXa3C6w", "http://www.clker.com/cliparts/K/w/R/r/V/Z/number-4-hi.png", "http://www.clker.com/cliparts/K/w/R/r/V/Z/number-4-hi.png"];
var memory_values = [];
var memory_tile_ids = [];
var tiles_flipped = 0;
Array.prototype.memory_tile_shuffle = function() {
var i = this.length,
j,
temp;
while (--i > 0) {
j = Math.floor(Math.random() * (i + 1));
temp = this[j];
this[j] = this[i];
this[i] = temp;
}
};
function newBoard() {
tiles_flipped = 0;
var output = "";
memory_array.memory_tile_shuffle();
for (var i = 0; i < memory_array.length; i++) {
output +=
'<div id="tile_' +
i +
'" onclick="memoryFlipTile(this,\'' +
memory_array[i] +
"')\"></div>";
}
document.getElementById("memory_board").innerHTML = output;
}
function memoryFlipTile(tile, val) {
//if the title is empty and array = 0 then the rest of code will perform
if (tile.innerHTML == "" && memory_values.length < 2) {
//the tile selected will have a white background and the val will be produced
tile.style.background = "#FFF";
var img= new Image();
img.src = val;
img.width="50";
img.height="50";
tile.appendChild(img);
//if the array equal = 0
if (memory_values.length == 0) {
//push the val and the title id to their respective arrays
memory_values.push(val);
memory_tile_ids.push(tile.id);
//if the array equal = 1
} else if (memory_values.length == 1) {
//push the val and the title id to their respective arrays
memory_values.push(val);
memory_tile_ids.push(tile.id);
//if memory_values values are the same
if (memory_values[0] == memory_values[1]) {
tiles_flipped += 2;
// Clear both arrays
memory_values = [];
memory_tile_ids = [];
// Check to see if the whole board is cleared
if (tiles_flipped == memory_array.length) {
alert("Board cleared... generating new board");
document.getElementById("memory_board").innerHTML = "";
newBoard();
}
} else {
// if the two flip tiles aren't of the same value
function flip2Back() {
// Flip the 2 tiles back over
var tile_1 = document.getElementById(memory_tile_ids[0]);
var tile_2 = document.getElementById(memory_tile_ids[1]);
tile_1.style.background = "orangered";
tile_1.innerHTML = "";
tile_2.style.background = "orangered";
tile_2.innerHTML = "";
// Clear both arrays
memory_values = [];
memory_tile_ids = [];
}
setTimeout(flip2Back, 700);
}
}
}
}
newBoard();
</script>
</body>
</html>
You can also test it here
Your code doesn't see the difference between a string representing a url, and a string with some text in it. It's both strings. So, in order to display the image, you'd need to do one of the following:
Create an <img> element, and set that elements src attribute to the url.
Add some css to make the element have a background-image with the url you have, and style that accordingly.
EDIT. Let's just do the first method, because it's a bit easier. The following will create an image with the correct source:
var imageElement = new Image();
imageElement.src = url;
and then we can put it inside an element, for example, putting it inside tile would be
tile.appendChild(imageElement);
EDIT 2. To transform the array of urls into an array of images, one could simply do this:
// your array of urls
var url_array = ["./naruto.gif","fakepath/pikachu.gif"];
// this will create a new array with the same length as url_array
var memory_array = new Array(url_array.length);
// loop through it to put the images in memory_array
for(var i = 0; i < memory_array.length; ++i){
memory_array[i] = new Image();
memory_array[i].src = url_array[i];
}
// now memory_array contains the right images with source set

Making an HTML page to display n rows of pascal's triangle, cannot array.push the current row to page

I am new to JavaScript, and decided to do some practice with displaying n rows of Pascal's triangle. I have everything working, and the rows are displayed in the console, however when I try to push the currentRow to the array of triangle, nothing shows up on the page. Here is how I am attempting to do so:
if (typeof currentRow !== 'undefined') {
console.log('Row ', i - 2);
currentRow = currentRow.join(' ');
console.log(currentRow);
console.log(triangle);
triangle.push('n', currentRow)
triangle = triangle.join('');
}
Any help/advice would be apreciated. I am sure this code is not that efficient (I know it is not optimal to just write out the first 3 rows). Below is a code snippet, and a jsfiddle.
https://jsfiddle.net/keuo8za0/
var row0 = [1];
var row1 = [1, 1];
var row2 = [1, 2, 1];
row0 = row0.join(' ');
row1 = row1.join(' ');
row2 = row2.join(' ');
var triangle = [row0];
triangle.push('\n', row1);
triangle.push('\n', row2);
triangle = triangle.join('');
lastRow = [1, 2, 1];
var submit = document.getElementById('submit');
function buildTriangle(pascalNumber) {
for (let i = 4; i < pascalNumber; i++) {
if (typeof currentRow !== 'undefined') {
console.log('Row ', i - 2);
currentRow = currentRow.join(' ');
console.log(currentRow);
console.log(triangle);
}
var x = i;
var currentRow = [1, 1];
for (let y = 1; y + 1 < x; y++) {
var nextNumber = (lastRow[y - 1] + lastRow[y]);
currentRow.splice(1, 0, nextNumber);
}
lastRow = currentRow;
}
}
function drawTriangle() {
document.getElementById('triangle').innerText = triangle;
}
submit.onclick = function() {
var rownum = document.getElementById('pn').value;
buildTriangle(rownum - 1);
drawTriangle();
return false;
}
body {
background: #4286f4;
font-family: arial;
}
h1 {
font-size: 36px;
text-align: center;
}
h1:hover {
color: #ff35c5;
}
form {
font: sans-serif;
text-align: center;
}
p {
font-size: 36px;
font: sans-serif;
text-align: center;
}
#map {
margin: 0 auto;
width: 80%;
height: 80%;
}
<html>
<head>
<title>Pascal's Triangle</title>
<link rel="stylesheet" href="fancy.css" />
</head>
<body>
<h1>Pascal's Triangle</h1>
<form id='numberOfRows'>
Number of Rows:<br>
<input id='pn' type='number'><br>
<button id='submit'>Submit</button>
</form>
<p id='triangle'></p>
<script src="triangler.js"></script>
</body>
</html>
Interesting... I did it row by row. Found really good help from google..
<style>
body {
background: #4286f4;
font-family: arial;
}
h1 {
font-size: 36px;
text-align: center;
}
h1:hover {
color: #ff35c5;
}
form {
font: sans-serif;
text-align: center;
}
p {
font-size: 36px;
font: sans-serif;
text-align: center;
}
#map {
margin: 0 auto;
width: 80%;
height: 80%;
}
</style>
<h1>Pascal's Triangle</h1>
<form id='numberOfRows'>
Number of Rows:<br>
<input id='pn' type='number'><br>
<button id='submit'>Submit</button>
</form>
<p id='triangle'></p>
<script>
var div = document.getElementById('triangle');
submit.onclick = function() {
div.innerHTML = "";
var rownum = document.getElementById('pn').value;
printPascal(rownum);
return false;
};
function printPascal(n) {
// Iterate through every line and
// print entries in it
for (var line=0; line < n; line++)
{
var lineHTML = "<div class='text-center'>";
// Every line has number of
// integers equal to line
// number
for (var i = 0; i <= line; i++) {
lineHTML += "" + binomialCoeff(line, i) + " ";
}
lineHTML += "</div>\n";
div.innerHTML += lineHTML;
}
}
// for details of this function
function binomialCoeff(n, k)
{
var res = 1;
if (k > n - k)
k = n - k;
for (var i = 0; i < k; ++i)
{
res *= (n - i);
res /= (i + 1);
}
return res;
}
</script>

Creating a card matching game

I want to create a card matching game but I have an issue showing the images that are supposed to be hidden. When I click on a card, the path of the image shows instead of the actual image.
Here are all the codes that I have written:
div#card_board {
background: #ccc;
border: #999 1px solid;
width: 710px;
height: 600px;
padding: 24px;
margin: 0px auto;
}
div#card_board>div {
background: url(cardQtion.jpg) no-repeat;
background-size: 100%;
border: #000 1px solid;
width: 114px;
height: 132px;
float: left;
margin: 10px;
padding: 20px;
font-size: 64px;
cursor: pointer;
text-align: center;
}
<script>
var cardArray = new Array();
cardArray[0] = new Image();
cardArray[0].src = 'cardA.jpg';
cardArray[1] = new Image();
cardArray[1].src = 'cardA.jpg';
cardArray[2] = new Image();
cardArray[2].src = 'cardB.jpg';
cardArray[3] = new Image();
cardArray[3].src = 'cardB.jpg';
cardArray[4] = new Image();
cardArray[4].src = 'cardC.jpg';
cardArray[5] = new Image();
cardArray[5].src = 'cardC.jpg';
cardArray[6] = new Image();
cardArray[6].src = 'cardD.jpg';
cardArray[7] = new Image();
cardArray[7].src = 'cardD.jpg';
cardArray[8] = new Image();
cardArray[8].src = 'cardE.jpg';
cardArray[9] = new Image();
cardArray[9].src = 'cardE.jpg';
cardArray[10] = new Image();
cardArray[10].src = 'cardF.jpg';
cardArray[11] = new Image();
cardArray[11].src = 'cardF.jpg';
var cardVal = [];
var cardIDs = [];
var cardBackFace = 0;
Array.prototype.cardMix = function() {
var i = this.length,
j, temp;
while (--i > 0) {
j = Math.floor(Math.random() * (i + 1));
temp = this[j];
this[j] = this[i];
this[i] = temp;
}
}
function newBoard() {
cardBackFace = 0;
var output = "";
cardArray.cardMix();
for (var i = 0; i < cardArray.length; i++) {
output += '<div id="card_' + i + '" onclick="cardBackcard(this,\'' + cardArray[i].src + '\')"></div>';
}
document.getElementById('card_board').innerHTML = output;
}
function cardBackcard(tile, val) {
if (tile.innerHTML == "" && cardVal.length < 2) {
tile.style.background = '#FFF';
tile.innerHTML = val;
if (cardVal.length == 0) {
cardVal.push(val);
cardIDs.push(tile.id);
} else if (cardVal.length == 1) {
cardVal.push(val);
cardIDs.push(tile.id);
if (cardVal[0] == cardVal[1]) {
cardBackFace += 2;
cardVal = [];
cardIDs = [];
if (cardBackFace == cardArray.length) {
alert("Board cleared... generating new board");
document.getElementById('card_board').innerHTML = "";
newBoard();
}
} else {
function card2Back() {
var card_1 = document.getElementById(cardIDs[0]);
var card_2 = document.getElementById(cardIDs[1]);
card_1.style.background = 'url(cardQtion.jpg) no-repeat';
card_1.innerHTML = "";
card_2.style.background = 'url(cardQtion.jpg) no-repeat';
card_2.innerHTML = "";
cardVal = [];
cardIDs = [];
}
setTimeout(card2Back, 700);
}
}
}
}
</script>
<body>
<div id="card_board"></div>
<script>
newBoard();
</script>
</body>
You have some less than optimal code and frankly mine is only a refactor of that and has much that can be improved - study up.
Given that, here is the refactor:
I really dislike event in markup SO I moved that click handler invocation right into the code.
I saw two sets of JavaScript in your page why? I simply put them both in one.(see the last line of this).
Your array of images thing was not working and verbose so I used an array of names and created an array of images from that.
Insertion of an element is different than text so I used tile.appendChild(cardArray[cardIndex]); instead
Code:
// create an array of card images
var cardArray = [];
var cards = ['cardA.jpg', 'cardB.jpg', 'cardC.jpg', 'cardD.jpg', 'cardE.jpg', 'cardF.jpg'];
for (var i = 0; i < cards.length; i++) {
var im = new Image();
im.src = cards[i];
im.alt = cards[i];
cardArray.push(im);
cardArray.push(im);
}
var cardVal = [];
var cardIDs = [];
var cardBackFace = 0;
Array.prototype.cardMix = function() {
var i = this.length,
j, temp;
while (--i > 0) {
j = Math.floor(Math.random() * (i + 1));
temp = this[j];
this[j] = this[i];
this[i] = temp;
}
}
function newBoard() {
cardBackFace = 0;
var output = "";
cardArray.cardMix();
for (var i = 0; i < cardArray.length; i++) {
output += '<div id="card_' + i + '" class="cardcontainer" data-card="' + i + '"></div>';
}
document.getElementById('card_board').innerHTML = output;
var classname = document.getElementsByClassName("cardcontainer");
for (var i = 0; i < classname.length; i++) {
classname[i].addEventListener('click', cardBackcard, false);
}
}
function card2Back() {
var card_1 = document.getElementById(cardIDs[0]);
var card_2 = document.getElementById(cardIDs[1]);
card_1.style.background = "url('cardQtion.jpg') no-repeat";
card_1.innerHTML = "";
card_2.style.background = "url('cardQtion.jpg') no-repeat";
card_2.innerHTML = "";
cardVal = [];
cardIDs = [];
}
function cardBackcard() {
// these used to be in the HTML as parameters, I refactored to pass `this`
// and then use the attribute which is the index of the card it had
var tile = this;
//multiply by 1 to get number, could use parseInt but I did not
var cardIndex = this.getAttribute("data-card") *1;
if (!(tile.innerHTML == "" && cardVal.length < 2)) return;
tile.style.background = '#FFF';
tile.appendChild(cardArray[cardIndex]);
if (!(cardVal.length == 0 && cardVal[0] == cardVal[1])) return;
cardVal.push(cardIndex);
cardIDs.push(tile.id);
if (cardVal.length == 1) {
if (cardVal[0] == cardVal[1]) {
cardBackFace += 2;
cardVal = [];
cardIDs = [];
if (cardBackFace == cardArray.length) {
alert("Board cleared... generating new board");
document.getElementById('card_board').innerHTML = "";
newBoard();
}
} else {
setTimeout(card2Back, 700);
}
}
}
newBoard();

Merge two HTML tables using Javascript Objects as data feed?

I am going to have multiple arrays of arrays and I want to make objects from the array and then merge it into one table. I already did that, however I need help using the object to make one larger table?
If a key exists in one object but not the others the value can just be blank for the object the key doesnt exist. I am able to make multiple different tables but how can I merge them to make the table one larger one?
var data =[["default_PROJECT","Allow","Connect","Allow","AddComment","Allow","Write",
"Allow","ViewComments","Allow","ExportData","Allow","ExportImage","Allow","ViewUnderlyingData","Allow","Read","Allow","ShareView","Allow","Filter"],
["Allow","ExportImage","Allow","Write","Allow","ViewComments",
"Allow","ShareView","Allow","Filter","Allow","ExportData","Allow","Connect","Allow",
"Read","Allow","ViewUnderlyingData","Allow","AddComment","Allow","ViewComments","Deny","ExportData","Allow",
"AddComment","Deny","Write","Allow","Read","Deny","ExportXml","Deny","ShareView","Allow","Connect","Allow","ChangeHierarchy","Allow",
"WebAuthoring","Deny","ViewUnderlyingData","Deny","Filter","Deny","ExportImage"]];
var result = [];
for(var i = 0, len = data.length; i < len; i++) {
var list = data[i];
result[i] = { name: list[0] };
for (var j = list.length - 1; j >= 1; j = j - 2) {
var key = list[j];
var value = list[j - 1];
if( result[i][key] !== "Deny" ) {
result[i][key] = value;
}
}
}
console.log(result);
var resultElement = document.getElementById('result1');
var tpl = '';
for(var t = 0, tLen = result.length; t < tLen; t++) {
var item = result[t];
tpl+= '<table align=center style="width:25%;">' +
'<thead>' +
'<tr><td colspan="2">Project: ' + item.name + '</td></tr>' +
'<tr><th>Permission</th><th>Value</th></tr>' +
'</thead>' +
'<tbody>'
;
for(var key in item) {
if(!item.hasOwnProperty(key) || key === 'name') { continue; }
if(item[key] == "Allow"){
tpl += '<tr style="background-color:greenyellow;"><td>'+ key +'</td><td>'+ item[key] +'</td></tr>';
}
else{
tpl += '<tr style="background-color:red;"><td>'+ key +'</td><td>'+ item[key] +'</td></tr>';
}
}
}
resultElement.innerHTML = tpl;
table { text-align: left; width: 100%; margin-bottom: 50px; border-collapse: collapse;}
td, th { width: 50%; border: 1px solid black; line-height: 1; padding:2px 10px;}
[colspan="2"] { color: blue; font-weight: bolder;text-transform: uppercase; text-align: center;}
<div id="result1"></div>
http://jsfiddle.net/h2s17hac/
This merges the two tables.
Fiddle
var data =[["default_PROJECT","Allow","Connect","Allow","AddComment","Allow","Write",
"Allow","ViewComments","Allow","ExportData","Allow","ExportImage","Allow","ViewUnderlyingData","Allow","Read","Allow","ShareView","Allow","Filter"],
["test_PROJECT", "Allow","ExportImage","Allow","Write","Allow","ViewComments",
"Allow","ShareView","Allow","Filter","Allow","ExportData","Allow","Connect","Allow",
"Read","Allow","ViewUnderlyingData","Allow","AddComment","Allow","ViewComments","Deny","ExportData","Allow",
"AddComment","Deny","Write","Allow","Read","Deny","ExportXml","Deny","ShareView","Allow","Connect","Allow","ChangeHierarchy","Allow",
"WebAuthoring","Deny","ViewUnderlyingData","Deny","Filter","Deny","ExportImage"]];
function makeObjects(data){
result = [];
for(var i = 0, len = data.length; i < len; i++) {
var list = data[i];
result[i] = { Name: list[0] };
for (var j = list.length - 1; j >= 1; j = j - 2) {
var key = list[j];
var value = list[j - 1];
if( result[i][key] !== "Deny" ) {
result[i][key] = value;
}
}
}
return result;
}
function sortObject(obj) {
return Object.keys(obj).sort().reduce(function (result, key) {
result[key] = obj[key];
return result;
}, {});
}
function getKeys(data){
var keys = [];
for(i=0; i<data.length; i++){
key = Object.keys(data[i]);
for(j =0; j<key.length; j++){
if(keys.indexOf(key[j]) == -1){
keys.push(key[j]);
}
}
}
return keys;
}
function addMissingKeys(keys, data){
var filtData = [];
for(i=0; i<data.length; i++){
for(j=0; j<keys.length; j++){
if(data[i][keys[j]] == undefined){
data[i][keys[j]] = "";
}
}
}
for(num=0; num<data.length; num++){
filtData.push(sortObject(data[num]));
}
return filtData;
}
var dataa = makeObjects(data);
var keys = getKeys(dataa);
var filtData = addMissingKeys(keys, dataa);
console.log(filtData);
var resultElement = document.getElementById('result1');
var tpl = '<table align=center style="width:75%;">';
for(var t = 0, tLen = filtData.length; t < tLen; t++) {
var item = filtData[t];
tpl+= '<tr><td>' + item.Name + '</td>';
for(var key in item) {
if(!item.hasOwnProperty(key) || key === 'Name') { continue; }
if(item[key] != "") {
if(item[key] == "Allow"){
tpl += '<td style="background-color:greenyellow;">'+ key +':<br>'+ item[key] +'</td>';
}
else{
tpl += '<td style="background-color:red;">'+ key +':<br>'+ item[key] +'</td>';
}
} else {
tpl += '<td></td>';
}
}
tpl += '</tr>';
}
tpl += '</table>';
resultElement.innerHTML = tpl;
table { text-align: left; width: 100%; margin-bottom: 50px; border-collapse: collapse;}
td, th { width: 50%; border: 1px solid black; line-height: 1; padding:2px 10px;}
[colspan="2"] { color: blue; font-weight: bolder;text-transform: uppercase; text-align: center;}
<div id="result1"></div>
<div id="test"></div>

Categories

Resources