I am trying to make a basic sensor pad for HTML (JavaScript), which creates 500 small divs which then turn red on mouse hover. However, when I tried it, nothing was created
example.html
<!DOCTYPE html>
<html>
<head>
<title>SensorPad Test</title>
<link rel="stylesheet" href="styles.css" type="text/css">
<script type="text/javascript" src="SensorPad.js">
window.onload = createSensor;
</script>
</head>
</html>
styles.css
.sPad{
width: 0.4px;
height: 0.4px;
background-color: #EEE;
border: 0.1px solid #000;
}
.uPad{
background-color: #F00;
}
SensorPad.js
var sPos;
var count = 1;
function createSensor(){
for(var i = 0; i < 500; ++i){
var pad = document.createElement('div');
pad.className = 'sPad';
pad.id = 'pad' + count.toString();
pad.onmousehover = function(){sPos = parseInt(pad.id); clearPads(); pad.className = 'uPad';};
count++;
}
}
function clearPads(){
for(var i = 1; i <= count; ++i){
var n = 'pad' + i.toString();
var p = document.getElementById(n);
p.className = 'sPad';
}
}
You're missing
document.body.appendChild(pad);
First the code will not run because of the way you added the JavaScript
<script type="text/javascript" src="SensorPad.js">
window.onload = createSensor;
</script>
you can not have code inside and a src
<script type="text/javascript" src="SensorPad.js"></src>
<script type="text/javascript"
window.onload = createSensor;
</script>
First, you need to use separate script tags - one for the external reference and another for the onload.
As for the divs, you're creating them but you're not adding them to the DOM.
for(var i = 0; i < 500; ++i){
var pad = document.createElement('div');
pad.className = 'sPad';
pad.id = 'pad' + count.toString();
pad.onmousehover = function(){sPos = parseInt(pad.id); clearPads(); pad.className = 'uPad';};
document.body.appendChild(pad)
count++;
}
EDIT: Addressing Teemu's concern you might simply want to use CSS for that hover instead so:
for(var i = 0; i < 500; ++i){
var pad = document.createElement('div');
pad.className = 'sPad';
pad.id = 'pad' + i.toString();
document.body.appendChild(pad)
}
css
.sPad{
width: 0.4px;
height: 0.4px;
background-color: #EEE;
border: 0.1px solid #000;
}
.sPad:hover{
background-color: #F00;
}
Related
Can anyone help me on Javascript coding? Lines13-14 i try to create 9x div(class="square") but i get 18 childnodes when i check container from console. It also prints 18 in total?
Second issue is about resetbutton. When i try to clear container childnodes to start a new game it gives error. (maybe there's no need to add some code to clear container?) Thank you.
// Create div elements inside container according to difficulty
for (let i = 0; i < difficulty; i++) {
container.appendChild(createDiv());
}
function createDiv() {
// create a div element and assign "square" class
let div = document.createElement("div");
div.classList.toggle("square");
return div;
};
function resetGame () {
// Clean boxes
for (let i = 0; i < difficulty; i++) {
container.removeChild(container.childNodes[i]);
}
var buttonReset = document.querySelector("#reset");
var container = document.querySelector("#boxes");
var difficulty = 9;
var h1 = document.querySelectorAll("h1");
var message = document.querySelector("#message");
var pickedColor = "";
// Listener for reset button
buttonReset.addEventListener("click", resetGame());
function newGame () {
// Create div elements inside container according to difficulty
for (let i = 0; i < difficulty; i++) {
container.appendChild(createDiv());
}
// Select all squares.
var squares = document.querySelectorAll(".square");
// Create and fill colors array
let colors = createColors();
// Pick a random color from colors
pickedColor = colors[
Math.floor(Math.random() * squares.length)
];
// Update text on screen
colorDisplay.textContent = pickedColor;
// Draw squares with colors and check clicked color.
for(let i = 0; i < squares.length; i++) {
// Add initial colors to squares
squares[i].style.backgroundColor = colors[i];
// Add click events to squares
squares[i].addEventListener("click", function() {
// check if clickedColor is pickedColor.
if (this.style.backgroundColor === pickedColor) {
message.textContent = "Yes, you've found the color";
//change all square colors to pickedColor
for (let i = 0; i < difficulty; i++) {
// Add initial colors to squares
squares[i].style.backgroundColor = pickedColor;
};
h1.forEach(function(item) {
item.style.backgroundColor = pickedColor;
});
} else {
message.textContent = "Please try again!"
this.style.backgroundColor = "#232323";
}
});
};
}
function createColors() {
let createdList = [];
for(let i = 0; i < difficulty; i++) {
createdList.push("rgb(" +
Math.floor(Math.random() * 256) + ", " +
Math.floor(Math.random() * 256) + ", " +
Math.floor(Math.random() * 256) + ")");
};
return createdList;
};
function createDiv() {
// create a div element and assign "square" class
let div = document.createElement("div");
div.classList.toggle("square");
return div;
};
function resetGame () {
/// Clean boxes
for (let i = 0; i < difficulty; i++) {
container.removeChild(container.childNodes[i]);
}
// Create new game
newGame();
};
newGame(); // Only for first run
body {
background-color: #232323;
}
h1 {
color: white;
}
.square {
background: greenyellow;
float: left;
margin: 1.66%;
padding-bottom: 30%;
width: 30%;
}
#container {
margin: 0 auto;
max-width: 800px;
}
#stripe {
background: white;
color: black;
height: 30px;
text-align: center;
}
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<title>Color Game</title>
</head>
<body>
<h1 class="display-4">THE GREAT</h1>
<h1 class="display-2"><span id="colorDisplay">RGB(175, 203, 2)</span></h1>
<h1 class="display-4">GUESSING GAME</h1>
<div id="stripe">
<button id="reset">NEW COLORS</button>
<span id="message"></span>
</div>
<!-- Color boxes -->
<div class="container" id="boxes"></div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#2.0.0-next.4/dist/umd/index.min.js" integrity="sha384-AWosBrv7t83vzfQDzCZrtcVWT9tFVGuP7uL1EqwhTLscYSCGShI9+FOYrSL1wQYT" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</body>
</html>
For the first problem of having 18 divs instead of 9 in is because newGame method is called twice. One is at the end of code, the other one is in this line:
// Listener for reset button
buttonReset.addEventListener("click", resetGame());
The resetGame method is called there but it should be just passed as it is:
buttonReset.addEventListener("click", resetGame);
For the second problem of resetGame method not working as expected is that you are modifying the array that is being accessed (container.childNodes) in the loop.
That makes your i skip the element next to the each removed one.
Your difficulty may eventually become larger than childNodesCount
One solution is that do not remove items immediately, accumulate them in an array array and then remove based on that array
const toBeRemoved = []
for (let i = 0; i < difficulty; i++) {
toBeRemoved.push(container.childNodes[i]);
}
toBeRemoved.forEach(child => {
container.removeChild(child);
})
OR, another solution is that copy the childNodes to another variable so when you modify the original childNodes the copied array does not get affected:
const arrayOfChildren = Array.from(container.childNodes)
for (let i = 0; i < difficulty; i++) {
container.removeChild(arrayOfChildren[i]);
}
After fixing both problems:
var buttonReset = document.querySelector("#reset");
var container = document.querySelector("#boxes");
var difficulty = 9;
var h1 = document.querySelectorAll("h1");
var message = document.querySelector("#message");
var pickedColor = "";
// Listener for reset button
buttonReset.addEventListener("click", resetGame);
function newGame() {
// Create div elements inside container according to difficulty
for (let i = 0; i < difficulty; i++) {
container.appendChild(createDiv());
}
// Select all squares.
var squares = document.querySelectorAll(".square");
// Create and fill colors array
let colors = createColors();
// Pick a random color from colors
pickedColor = colors[
Math.floor(Math.random() * squares.length)
];
// Update text on screen
colorDisplay.textContent = pickedColor;
// Draw squares with colors and check clicked color.
for (let i = 0; i < squares.length; i++) {
// Add initial colors to squares
squares[i].style.backgroundColor = colors[i];
// Add click events to squares
squares[i].addEventListener("click", function() {
// check if clickedColor is pickedColor.
if (this.style.backgroundColor === pickedColor) {
message.textContent = "Yes, you've found the color";
//change all square colors to pickedColor
for (let i = 0; i < difficulty; i++) {
// Add initial colors to squares
squares[i].style.backgroundColor = pickedColor;
};
h1.forEach(function(item) {
item.style.backgroundColor = pickedColor;
});
} else {
message.textContent = "Please try again!"
this.style.backgroundColor = "#232323";
}
});
};
}
function createColors() {
let createdList = [];
for (let i = 0; i < difficulty; i++) {
createdList.push("rgb(" +
Math.floor(Math.random() * 256) + ", " +
Math.floor(Math.random() * 256) + ", " +
Math.floor(Math.random() * 256) + ")");
};
return createdList;
};
function createDiv() {
// create a div element and assign "square" class
let div = document.createElement("div");
div.classList.toggle("square");
return div;
};
function resetGame() {
/// Clean boxes
const arrayOfChildren = Array.from(container.childNodes)
for (let i = 0; i < difficulty; i++) {
container.removeChild(arrayOfChildren[i]);
}
// Create new game
newGame();
};
newGame(); // Only for first run
body {
background-color: #232323;
}
h1 {
color: white;
}
.square {
background: greenyellow;
float: left;
margin: 1.66%;
padding-bottom: 30%;
width: 30%;
}
#container {
margin: 0 auto;
max-width: 800px;
}
#stripe {
background: white;
color: black;
height: 30px;
text-align: center;
}
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<title>Color Game</title>
</head>
<body>
<h1 class="display-4">THE GREAT</h1>
<h1 class="display-2"><span id="colorDisplay">RGB(175, 203, 2)</span></h1>
<h1 class="display-4">GUESSING GAME</h1>
<div id="stripe">
<button id="reset">NEW COLORS</button>
<span id="message"></span>
</div>
<!-- Color boxes -->
<div class="container" id="boxes"></div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#2.0.0-next.4/dist/umd/index.min.js" integrity="sha384-AWosBrv7t83vzfQDzCZrtcVWT9tFVGuP7uL1EqwhTLscYSCGShI9+FOYrSL1wQYT" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</body>
</html>
In this program I created object and instances of it and stored those instances in array. I am retrieving array index by getting the modulo of minutes with the length of the array. I am trying to display link in div tag and I should be able to see different link every minute. Upon clicking link it should show different url. and set the timer to run every minute. For that I have created setInterval(). but it doesn't seem to work. Can anyone help me?
code:
<!DOCTYPE html>
<html>
<head>
<style>
.myDiv{
width: 750px;
height: 150px;
border: #CED8BC 3px solid;
border-radius: 20px;
position: absolute;
top: 30%;
left: 20%;
}
div p {
text-align: center;
font-family: monospace;
font-size: 30px;
}
a{
text-align: center;
text-decoration: none;
color: #3bb570;
}
a:hover{
color:#efa5db
}
</style>
<title>lab15</title>
</head>
<body background="lab15_images/pink.jpg">
<div class="myDiv" id="div">
<p> Click on the link to see a website. </p>
<!-- <p><b> </b></p> -->
<p id="link"> </p>
</div>
<script>
function site(the_url, website_name) {
this.the_url = the_url;
this.website_name = website_name;
}
var myWebsite = new site("http://www.cnn.com/", "CNN");
var myWebsite2 = new site("http://www.bbc.com/news", "BBC");
var myWebsite3 = new site("http://www.foxnews.com/", "FOX NEWS");
var myWebsite4 = new site("http://abcnews.go.com/", "ABC NEWS");
var myWebsite5 = new site("https://www.cbsnews.com/", "CBS NEWS");
var instances = new Array(myWebsite, myWebsite2, myWebsite3, myWebsite4, myWebsite5);
setInterval(changeLink, 60000);
function changeLink() {
var n = new Date().getMinutes();
var index = n % instances.length
var site = instances[index]
var counter = 0;
var ele = document.getElementbyId("link");
ele.innerHTML = instances[counter];
counter++;
if(counter >= instances.length) {
counter = 0;
}
var a = document.createElement('a');
var myDiv = document.getElementbyId("div");
a.href = site.the_url;
a.innerHTML = site.website_name
myDiv.appendChild(a);
document.body.appendChild(myDiv);
}
</script>
</body>
</html>
Fixed your semicolons and getElementById typos. Here is the working code.
function site(the_url, website_name) {
this.the_url = the_url;
this.website_name = website_name;
}
var myWebsite = new site("http://www.cnn.com/", "CNN");
var myWebsite2 = new site("http://www.bbc.com/news", "BBC");
var myWebsite3 = new site("http://www.foxnews.com/", "FOX NEWS");
var myWebsite4 = new site("http://abcnews.go.com/", "ABC NEWS");
var myWebsite5 = new site("https://www.cbsnews.com/", "CBS NEWS");
var instances = new Array(myWebsite, myWebsite2, myWebsite3, myWebsite4, myWebsite5);
// call changeLink once to display on page load
changeLink();
// interval changed to 3 seconds so that you dont need to wait a minute for the result
setInterval(changeLink, 3000);
function changeLink() {
var n = new Date().getMinutes();
var index = n % instances.length;
var site = instances[index];
var counter = 0;
var ele = document.getElementById("link");
counter++;
if (counter >= instances.length) {
counter = 0;
}
var a = document.createElement('a');
var myDiv = document.getElementById("div");
a.href = site.the_url;
a.innerHTML = site.website_name;
ele.innerHTML = '';
ele.appendChild(a);
}
.myDiv {
width: 750px;
height: 150px;
border: #CED8BC 3px solid;
border-radius: 20px;
position: absolute;
top: 30%;
left: 20%;
}
div p {
text-align: center;
font-family: monospace;
font-size: 30px;
}
a {
text-align: center;
text-decoration: none;
color: #3bb570;
}
a:hover {
color: #efa5db
}
<!DOCTYPE html>
<html>
<head>
<style>
</style>
<title>lab15</title>
</head>
<body background="lab15_images/pink.jpg">
<div class="myDiv" id="div">
<p> Click on the link to see a website. </p>
<!-- <p><b> </b></p> -->
<p id="link"> </p>
</div>
</body>
</html>
Move var counter = 0; out of the function.
Also, as #guest271314 pointed, you have to capitialize the by in:
var ele = document.getElementById("link");
/* ... */
var myDiv = document.getElementbyId("div");
Final code:
var counter = 0;
function changeLink() {
var n = new Date().getMinutes();
var index = n % instances.length
var site = instances[index]
//var counter = 0;
var ele = document.getElementById("link"); //Capitalize By
ele.innerHTML = instances[counter];
counter++;
if (counter >= instances.length) {
counter = 0;
}
var a = document.createElement('a');
var myDiv = document.getElementById("div"); //Capitalize By
a.href = site.the_url;
a.innerHTML = site.website_name
myDiv.appendChild(a);
document.body.appendChild(myDiv);
}
I recently started learning how to use JavaScript in my webpage. My exercise today is to make a button that can give me a V shape.
The code to create the V shape is fine, but it doesn't work when I try to put it in a click handler (i.e. oBtn.click = function (){};).
In the HTML document I have the following code:
<style>
div{
width: 50px;
height: 50px;
border: 1px red solid;
position: absolute;
line-height: 50px;
text-align: center;
margin: 5px;
}
</style>
<script type="text/javascript">
window.onload = function (){
var oBody = document.getElementById('body');
var aDiv = document.getElementsByTagName('div');
var oBtn1 = document.getElementById('btn1');
for (var i = 0; i < 9; i++) {
oBody.innerHTML += '<div>'+ i +'</div>';
}
for (var i = 0; i < aDiv.length; i++) {
aDiv[i].style.left =i*50+'px';
}
oBtn1.onclick = function (){
for (var i = 0; i < aDiv.length/2; i++) {
aDiv[i].style.top = 40+i*50+'px';
}
var x = aDiv.length;
for (var i = 4; i < x; i++) {
aDiv[i].style.top =x*50-i*50-50+40+'px';
}
};
};
</script>
I believe this is close to what you wanted. Runs in chrome, but may not in other browsers (notably IE). Doesn't work as a snippet, sorry. I suspect trying to modify all divs in the body is going to cause you trouble in the long term. A couple of things to notice:
You don't need to get the body by name, you can just use document.body (I'm making an assumption here - however giving an element the id "body" could easily cause confusion)
Your divs must be created before you try to get the array from the DOM
Event handlers are done using the commonly preferred method.
<html>
<head>
<style>
div{
width: 50px;
height: 50px;
border: 1px red solid;
position: absolute;
line-height: 50px;
text-align: center;
margin: 5px;
}
</style><script>
window.addEventListener("DOMContentLoaded", function () {
for (var i = 0; i < 9; i++) {
document.body.innerHTML += '<div>'+ i +'</div>';
}
var aDiv = document.getElementsByTagName('div');
for (var i = 0; i < aDiv.length; i++) {
aDiv[i].style.left =i*50+'px';
}
document.getElementById('btn1').addEventListener("click", function () {
for (var i = 0; i < aDiv.length/2; i++) {
aDiv[i].style.top = 40+i*50+'px';
}
var x = aDiv.length;
for (var i = 4; i < x; i++) {
aDiv[i].style.top =x*50-i*50-50+40+'px';
}
});
}, false);
</script>
</head>
<body>
<input type="button" id="btn1"><br />
</body>
</html>
If I understand this right, you want to execute 'oBtn1.onclick' as a click event? If so, do something like this
function buttonClick (){
for (var i = 0; i < aDiv.length/2; i++) {
aDiv[i].style.top = 40+i*50+'px';
}
oBtn1.addEventListener('click', buttonClick);
what that will do is as soon as the element that contains the id 'oBtn1' is clicked it will execute your for loop.
What does your html look like? If it looks kind of like the below snippet then it should be working, though you should look at using addEventListener for this kind of thing.
window.onload = function (){
var oBody = document.getElementById('body');
var aDiv = document.getElementsByTagName('div');
var oBtn1 = document.getElementById('btn1');
for (var i = 0; i < 9; i++) {
oBody.innerHTML += '<div>'+ i +'</div>';
}
for (var i = 0; i < aDiv.length; i++) {
aDiv[i].style.left =i*50+'px';
}
oBtn1.onclick = function (){
for (var i = 0; i < aDiv.length/2; i++) {
aDiv[i].style.top = 40+i*50+'px';
}
var x = aDiv.length;
for (var i = 4; i < x; i++) {
aDiv[i].style.top =x*50-i*50-50+40+'px';
}
};
};
div{
width: 50px;
height: 50px;
border: 1px red solid;
position: absolute;
line-height: 50px;
text-align: center;
margin: 5px;
}
<button id="btn1">press</button>
<div id="body"></div>
This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 6 years ago.
I am facing error at append child as the object null value error is there infact i have created the object in the top of script with document get element
and i am trying to get the issue resolve as left side is in there in the div need some help try to figure it out. Please as u read
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Game</title>
<style>
imgg{
position: absolute;
}
div{
width: 500px;
height: 500px;
position: absolute;
}
#rightSide { left: 500px;
border-left: 1px solid black }
</style>
<script>
var numberOfFaces =5 ;
var theLeftSide = document.getElementById("leftSide");
function generateFaces(){
for(var i = 1 ; i <= numberOfFaces ; i++)
{
var imgg = document.createElement("img");
imgg.src = "smile.png";
imgg.style.height = "100px";
imgg.style.width = "100px";
imgg.style.top = Math.random() *400 ;
imgg.style.left = Math.random() *400 ;
theLeftSide.appendChild(imgg);
}
}
</script>
</head>
<body onload="generateFaces()">
<h2>Matching Game</h2>
<p>Click on the extra smiling face on the left.</p>
<div id="leftSide"></div>
<div id="rightSide"></div>
</body>
</html>
document.getElementById("leftSide"); will give error if you put your script inside head. The reason being when js will try to parse this line but there is no such DOM present .
You can resolve it by using
window.onload
put the script tag before closing body tag
<body>
// Dom
<script>
// Rest of code
</script>
</body>
Using window.onload
<head>
//Rest of code
<script>
window.onload = function(){
var numberOfFaces =5 ;
var theLeftSide = document.getElementById("leftSide");
function generateFaces(){
for(var i = 1 ; i <= numberOfFaces ; i++)
{
var imgg = document.createElement("img");
imgg.src = "smile.png";
imgg.style.height = "100px";
imgg.style.width = "100px";
imgg.style.top = Math.random() *400 ;
imgg.style.left = Math.random() *400 ;
theLeftSide.appendChild(imgg);
}
}
}
</script>
</head>
Check this JSFIDDLE , script is wrapped in the body
Place your <script> as last-child of <body> as by the time you are accessing the element using DOM-api, element is not in the DOM
Set position to absolute
Add unit as px(pixel) while assigning top and left
var numberOfFaces = 5;
var theLeftSide = document.getElementById("leftSide");
function generateFaces() {
for (var i = 1; i <= numberOfFaces; i++) {
var imgg = document.createElement("img");
imgg.src = "http://i185.photobucket.com/albums/x304/metalife/transmetropolitan-smile.png";
imgg.style.height = "100px";
imgg.style.width = "100px";
imgg.style.position = 'absolute';
imgg.style.top = Math.random() * 400 + 'px';
imgg.style.left = Math.random() * 400 + 'px';
theLeftSide.appendChild(imgg);
}
}
imgg {
position: absolute;
}
div {
width: 500px;
height: 500px;
position: absolute;
}
#rightSide {
left: 500px;
border-left: 1px solid black
}
<body onload="generateFaces()">
<h2>Matching Game</h2>
<p>Click on the extra smiling face on the left.</p>
<div id="leftSide"></div>
<div id="rightSide"></div>
Hi I've got this code which is a memory board game. I would like to know if its possible to change the letters and put images instead. I am completely new to javaScript and I am trying to learn by editing and understanding open source code.. any help would be appreciated thanks!
This is the Javscript code:
var memory_array = ['A','A','B','B','C','C','D','D','E','E','F','F','G','G','H','H','I','I','J','J','K','K','L','L'];
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(tile.innerHTML == "" && memory_values.length < 2){
tile.style.background = '#FFF';
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] == 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 {
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(images/logo.jpg) no-repeat';
tile_1.innerHTML = "";
tile_2.style.background = 'url(images/logo.jpg) no-repeat';
tile_2.innerHTML = "";
// Clear both arrays
memory_values = [];
memory_tile_ids = [];
}
setTimeout(flip2Back, 700);
}
}
}
}
This is the HTML Code
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>The HTML5 Herald</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="script.js"></script>
</head>
<body>
<div id="memory_board"> </div>
<script> newBoard(); </script>
</body>
</html>
And finally this is the CSS code
div#memory_board{
background: #CCC;
border: #999 1px solid;
width: 800px;
height: 540px;
padding: 24px;
margin: 0px auto;
}
div#memory_board > div{
background: url(images/logo.jpg) no-repeat;
border: #000 1px solid;
width: 71px;
height: 71px;
float: left;
margin: 10px;
padding: 20px;
font-size: 64px;
cursor: pointer;
text-align:center;
}
Easy way to change your code to do what you want - instead of
tile.innerHTML = val;
do:
tile.innerHTML = '<img src="' + val + '.png"/>';
which should work if you have A.png, B.png and so on in the same location as index.html.
If you wanted to go more in-depth with it, I wrote a tutorial about doing this with an html5 framework some time ago (apologies for linking to our own website)