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
Related
I'm trying to build a visual representation of some famous sorting algorithms in javascript, but I can't understand why my code doesn't print each iteration even if the print function is in the for loop. I only get the final result.
This is the sorting function, in particular the selection sort algorithm:
function selectionSort(array) {
var i, j, min_idx;
let n = array.length;
for (i = 0; i < n-1; i++)
{
min_idx = i;
for (j = i + 1; j < n; j++)
{
if (array[j] < array[min_idx])
{
min_idx = j;
}
}
var temp = array[min_idx];
array[min_idx] = array[i];
array[i] = temp;
printArray(array);
}
}
And this is the printing function:
function printArray(array) {
document.getElementById('container').innerHTML ='';
for(let i = 0; i < array.length; i++)
{
document.getElementById('container').innerHTML += '<div class = "column '+i+'" id = "'+i+'" style = "height: '+array[i]+'px;"></div>';
}
}
Thank you a lot
It's what #Bravo states in the comments. The screen is updates at least 60 times per second, but it takes less time to do the sorting. So you need to add a timeout in a recursive loop so you can actually see the animation.
I replaced the first for loop with this recursive loop. I think the code it self-explanatory.
I did some optimization in your printArray(), where it takes time to constantly doing DOM changes. Instead, loop through to create a text string and then add it once to #container.innerHTML. There were also some faulty thinking in the value that you gave the visualized divs, where you only added the order (i), instead of adding the actual value (array[i]).
const iterationLegend = document.getElementById('iterations');
const containerDiv = document.getElementById('container');
const ANIMATION_SPEED = 1000;
const RESTART = 0;
var firstIteration;
function startSelectionSort(array) {
firstIteration = RESTART;
selectionSort(array);
}
function selectionSort(array) {
let min_idx = firstIteration,
n = array.length;
for (let j = firstIteration + 1; j < n; j++) {
if (array[j] < array[min_idx]) {
min_idx = j;
}
}
var temp = array[min_idx];
array[min_idx] = array[firstIteration];
array[firstIteration] = temp;
visualizeArray(array);
iterationLegend.textContent = 'iteration ' + firstIteration;
if (firstIteration < n - 1) {
firstIteration++;
setTimeout(selectionSort.bind(this, array), ANIMATION_SPEED);
} else {
iterationLegend.textContent = 'Done';
}
}
function visualizeArray(array) {
let elementStr = '';
let value = 0;
for (let i = 0; i < array.length; i++) {
value = array[i];
elementStr += `<div class="column${value}" data-value="${value}"></div>`;
}
containerDiv.innerHTML = elementStr;
}
startSelectionSort([2, 3, 5, 5, 1, 1, 1, 1, 4]);
fieldset {
display: inline;
}
#iterations {
font-size: 13px;
text-transform: uppercase;
}
#container {
display: inline-flex;
}
#container > div {
width: 10px;
height: 100px;
margin: 2px 1px 0px;
}
.column1 {
background-color: brown;
}
.column2 {
background-color: black;
}
.column3 {
background-color: teal;
}
.column4 {
background-color: red;
}
.column5 {
background-color: indigo;
}
<fieldset>
<legend id="iterations">Iterations</legend>
<div id="container"></div>
</fieldset>
I'm trying to use document.getElementByClassId().style.color to change the color of an element in my HTML document. I can see that it does add an inline style tag to the element but they are seemingly ignored by the browser.
I tried using the !important tag but that changed nothing. Here is my HTML document. I changed my CSS for the elements I want to modify into inline tags but they are ignored as well. Everything else works so far.
Here is my code (I'm a beginner please go easy on me :/).
//Only gets used to make the rows array.
var cells = [];
//Array that contains the entirety of the table element.
var rows = [];
//Random number to be used to color a random cell.
var rand = 0;
//Unique ID number that gets applied to each cell on the gameboard.
var id = 0;
//Calls cellMake.
var makeBoard = function(size) {
cellMake(size);
}
//Adds opening and closing tags at the beginning and end of each string then writes them to the rows array.
var rowMake = function(num) {
for(c = 0; num > c; c++) {
rows[c] = '<tr>' + cells[c] + '</tr>';
}
writeBoard();
}
//Writes cell elements to the cells array based on how many columns the makeBoard function was called for.
var cellMake = function(num) {
for(a = 0; num > a; a++) {
cells[a] = '';
for(b = 0; num > b; b++) {
cells[a] += '<td id="' + id + '" class="pixel">';
id++;
}
}
rowMake(num);
}
//Chooses random pixel from the board and sets its color.
var choosePixel = function() {
rand = Math.round(Math.random() * rows.length * rows.length);
console.log(rand);
document.getElementById(rand).style.color = 'red';
}
//Writes each element of the rows array onto the HTML document.
var writeBoard = function() {
for(d = 0; rows.length > d; d++) {
document.getElementById('gameboard').innerHTML += rows[d];
}
choosePixel();
}
window.onload = function() {
makeBoard(50);
}
<!DOCTYPE html>
<html>
<head>
<title>Can I write JS?</title>
<script src="script.js"></script>
<style>
body {
text-align: center;
background-color: black;
}
#gameboard {
display: inline-block;
margin: 0 auto;
padding-top: 5%;
}
.pixel {
height: 5px;
width: 5px;
}
</style>
</head>
<body>
<table id="gameboard"></table>
</body>
</html>
You have to style the backgroundColor instead of color, because the cells don't contain any text, to which the color would be applied to
//Only gets used to make the rows array.
var cells = [];
//Array that contains the entirety of the table element.
var rows = [];
//Random number to be used to color a random cell.
var rand = 0;
//Unique ID number that gets applied to each cell on the gameboard.
var id = 0;
//Calls cellMake.
var makeBoard = function(size) {
cellMake(size);
}
//Adds opening and closing tags at the beginning and end of each string then writes them to the rows array.
var rowMake = function(num) {
for(c = 0; num > c; c++) {
rows[c] = '<tr>' + cells[c] + '</tr>';
}
writeBoard();
}
//Writes cell elements to the cells array based on how many columns the makeBoard function was called for.
var cellMake = function(num) {
for(a = 0; num > a; a++) {
cells[a] = '';
for(b = 0; num > b; b++) {
cells[a] += '<td id="' + id + '" class="pixel"></td>';
id++;
}
}
rowMake(num);
}
//Chooses random pixel from the board and sets its color.
var choosePixel = function() {
rand = Math.round(Math.random() * rows.length * rows.length);
console.log(rand);
document.getElementById(rand).style.backgroundColor = 'red';
}
//Writes each element of the rows array onto the HTML document.
var writeBoard = function() {
for(d = 0; rows.length > d; d++) {
document.getElementById('gameboard').innerHTML += rows[d];
}
choosePixel();
}
window.onload = function() {
makeBoard(50);
}
<!DOCTYPE html>
<html>
<head>
<title>Can I write JS?</title>
<script src="script.js"></script>
<style>
body {
text-align: center;
background-color: black;
}
#gameboard {
display: inline-block;
margin: 0 auto;
padding-top: 5%;
}
.pixel {
height: 5px;
width: 5px;
}
</style>
</head>
<body>
<table id="gameboard"></table>
</body>
</html>
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
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();
I am trying to make a grid in an HTML using plain Javascript. I have a URL in which number is given and basis on that I am generating a grid.
My url is like this abc.html?num=5 and basis on this num=5 I need to generate a grid of 5x5 size.
Currently I am using jQuery but I want to see how we can do the same thing with plain Javascript. Here is my jsfiddle example.
Below is my full content of abc.html:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var defaultNum = 4;
var url = window.location.search;
var num = parseInt(url.split('num=')[1]) || defaultNum;
var container = $('#container');
var width = container.outerWidth();
createGrid(num);
function createGrid(n) {
if (!$.isNumeric(n) || n <= 0) return;
for (var i = 0; i < n * n; i++) {
var dimension = width / n;
var cell = $('<div/>').addClass('gridCell').css({
'width': dimension + 'px',
'height': dimension + 'px'
});
container.append(cell);
}
}
});
</script>
<style>
#container {
width: 300px;
height: 300px;
}
#container > .gridCell {
float: left;
padding: 0;
margin: 0;
border: 0;
outline: 1px solid;
}
</style>
</head>
<body>
<div id="container"></div>
</body>
</html>
How can I do the same thing with plain Javascript instead of using any libraries like jquery which I am using currently?
This can't be demonstrated in a jsfiddle because it requires access to the url. But here is the code, put it in an HTML and test it out:
<html>
<style>
#container {
width: 300px;
height: 300px;
}
#container > .gridCell {
float: left;
padding: 0;
margin: 0;
border: 0;
outline: 1px solid;
}
</style>
<body>
<div id="container">
</div>
<script>
// QueryString is the function that gets the num parameter.
// Source to this function: http://stackoverflow.com/questions/979975/how-to-get-the-value-from-the-url-parameter
var QueryString = function () {
// This function is anonymous, is executed immediately and
// the return value is assigned to QueryString!
var query_string = {};
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
// If first entry with this name
if (typeof query_string[pair[0]] === "undefined") {
query_string[pair[0]] = pair[1];
// If second entry with this name
} else if (typeof query_string[pair[0]] === "string") {
var arr = [ query_string[pair[0]], pair[1] ];
query_string[pair[0]] = arr;
// If third or later entry with this name
} else {
query_string[pair[0]].push(pair[1]);
}
}
return query_string;
} ();
var defaultNum = 3;
var num = parseInt(QueryString.num) || defaultNum;
var container = document.getElementById('container');
var width = container.offsetWidth;
createGrid(num);
function createGrid(n) {
// If n is not a number or smaller than 0
if(isNaN(n) || n <= 0)
return;
for(var i = 0; i < n*n; i++) {
var dimension = width/n;
var cell = document.createElement('div');
cell.className = cell.className + ' gridCell';
cell.style.width = dimension + 'px';
cell.style.height = dimension + 'px';
container.appendChild(cell);
}
}
</script>
</body>
</html>