Trying to display image in a game of memory - javascript

Okay, so this is my problem. I'm creating a game of memory with some images in it. I cannot understand how I would be able to display the image after setting it to display='none' with the for-loop onLoad function.
I've tried for a couple of hours now without result. =(
Anyone that can help me?
And also elem.id points to a td id so it's dynamic. It's tricky because in every td there is an img.
I sincerely appreciate your help.
This is my code:
var clicked = true;
var firstClick;
var secondClick;
var firstPlayer = true;
var addPointPlayer1 = 0;
var addPointPlayer2 = 0;
var totalPoints = 8;
function clickCard(elem){
//document.getElementsByTagName('img').style.display = "";
if(clicked){
firstClick = document.getElementById(elem.id);
// document.getElementsByName(/.img/).style.visibility="visible";
firstClick.style.backgroundColor= "white";
clicked = false;
}
else{
secondClick = document.getElementById(elem.id);
secondClick.style.backgroundColor = "white";
if(firstClick.innerHTML == secondClick.innerHTML){
firstClick.style.backgroundColor="white";
secondClick.style.backgroundColor="white";
if(firstPlayer){
addPointPlayer1++;
totalPoints--;
}
else{
addPointPlayer2++;
totalPoints--;
}
}
else {
alert('This is not a pair, player change');
firstClick.style.backgroundColor="#7f1a1a";
secondClick.style.backgroundColor="#7f1a1a";
if(firstPlayer){
firstPlayer = false;
}
else{
firstPlayer = true;
}
}
clicked = true;
}
//Keeping control of the winner
if(totalPoints == 0){
if(addPointPlayer1 > addPointPlayer2){
alert("Game over! Player 1 wins with " + addPointPlayer1 + " points" + addPointPlayer2);
}
else if (addPointPlayer1 == addPointPlayer2){
alert("This is a draw press cmd+R for a rematch");
}
else{
alert("Game over! Player 2 wins with " + addPointPlayer2 + " points against " + addPointPlayer1);
}
}
}
//creates a blank game-plan
function hideGamePlan(){
var images = document.getElementsByTagName('img');
for (i = 0; i < images.length;i++ ) {
images[i].style.display = "none";
}
}

If you've set the display to none, then somewhere else you should be setting the display to something - ie block.
I recommend this for help: http://www.w3schools.com/cssref/pr_class_display.asp

After if(clicked){firstClick = document.getElementById(elem.id);
I guess your problem is to find the children image tag element
if that is the case You may use find("img")
I mean
if(clicked){
firstClick = document.getElementById(elem.id);
elemtochange = firstClick.find("img");
// Changing image style here
elemtochange.style.display ="block";
}
Or you may want to look into Jquery to do the same for you by just
if (clicked){
$(elem).children("img").show(); // elem = Clicked element
}
Instead of show you may use hide to hide the element or toggle to toggle the display between show and hide on every click

I've solved this with
function clickCard(elem){
if(!clicked){
firstClick = document.getElementById(elem.id);
firstClick.style.backgroundColor= "white";
findImage[firstClick.id-1].style.visibility="visible";
clicked = true;
//alert(findImage);
}
else{
secondClick = document.getElementById(elem.id);
secondClick.style.backgroundColor = "white";
findImage[secondClick.id-1].style.visibility="visible";
// firstClick.getAttribute('src');
// secondClick.getAttribute('src');
if(firstClick.innerHTML == secondClick.innerHTML){
firstClick.style.backgroundColor="white";
secondClick.style.backgroundColor="white";
if(firstPlayer){
addPointPlayer1++;
totalPoints--;
}
else{
addPointPlayer2++;
totalPoints--;
}
}
else {
alert('This is not a pair, player change');
firstClick.style.backgroundColor="#7f1a1a";
secondClick.style.backgroundColor="#7f1a1a";
findImage[firstClick.id-1].style.visibility="hidden";
findImage[secondClick.id-1].style.visibility="hidden";
if(firstPlayer){
firstPlayer = false;
//findImage[elem.id-1].style.visibility="hidden";
}
else{
firstPlayer = true;
}
}
clicked = false;
}
//Keeping control of the winner
if(totalPoints == 0){
if(addPointPlayer1 > addPointPlayer2){
alert("Game over! Player 1 wins with " + addPointPlayer1 + " points" + addPointPlayer2);
}
else if (addPointPlayer1 == addPointPlayer2){
alert("This is a draw press cmd+R for a rematch");
}
else{
alert("Game over! Player 2 wins with " + addPointPlayer2 + " points against " + addPointPlayer1);
}
}
}
function hideGamePlan(){
findImage = document.getElementsByTagName('img');
for (i = 0; i < findImage.length;i++ ) {
findImage[i].style.visibility = "hidden";
}
}

Thanks for all the response's! I ended up just placing the submit buttons up top..
<form action = "/memory-game/index.php" method = "POST">
<input type="submit" name="dog" value="Dog" />
<input type="submit" name="cat" value="Cat" />
<input type="submit" name="fish" value="Fish" />
<input type="submit" name="zoo" value="Zoo" />
<input type="submit" name="xmas" value="Xmas" />
<input type="submit" name="pen" value="Pengins" />
</form>
Then for the other page did this:
if(isset($_POST['dog'])){$currentArr = $dogArr;}
elseif(isset($_POST['cat'])){$currentArr = $catArr;}
elseif(isset($_POST['fish'])){$currentArr = $fishArr;}
elseif(isset($_POST['xmas'])){$currentArr = $xmasArr;}
elseif(isset($_POST['pen'])){$currentArr = $penginArr;}
elseif(isset($_POST['zoo'])){$currentArr = $zooArr;}

Related

Changing image while clicking button in html/javascript

Please i want to change the temperature level in each button click. In a way to have a white arrow in a first time, two white arrow i a seconde time .... i have images withe 1 arrow, 2 arrow ext.
this my image in html :
<div id="WBR"><img src="assets/AWImages/V0.png"></div>
<button id= "HI" class="circle" >+</button>
I simulate the button click in javascript like this :
let addb = document.querySelector('#HI');
addb.addEventListener('click', () =>{
input.value = parseInt(input.value)+1;
if((input.value)<5)
{
socket.emit('Value of hum changed',input.value);
}
else
{
input.value =4;
}
});
I really appreciate ur help ;)
let addb = document.querySelector('#WBR');
let wbr = document.querySelector('#HI');
var f = document.querySelector('#f');
var Score = 0;
var win = 5;
var gameOver = false;
addb.addEventListener("click", function () {
if (!gameOver) {
Score++ ;
if (Score == win) {
gameOver = true;
addb.style.color = "green";
}
f.innerHTML = Score;
}
});
<div id="WBR"><img src="assets/AWImages/V0.png"></div>
<button id= "HI" class="circle" >+</button>
<p id="f">0</p>

why wont my else if statements work

Hello everyone i am not really sure why my else if statements aren't working as i intend to have them run on the click of a button and each else if question run until one of them is true and returns the 'correct' or 'wrong' boxes. Are my else if statements even being called on correctly? And if so am i referring to the 'correctAnswer' correctly? Thanks in advance!:)(oh and by the way the display style of the 'wrong' and 'correct' divs are set to 'none' in an external css stylesheet)
The Javascript:
var gameOn = false;
var score;
var interval;
Array.prototype.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;
}//while loop bracket
return this;
}
function stopGame() {
gameOn = false;
if (interval) {
clearInterval(interval);
interval = null;
}//if interval bracket
document.getElementById("startreset").innerHTML = "Start Game";
document.getElementById("time-remaining").style.display = "";
}//function stopGame bracket
//if we click on the start/reset
document.getElementById("startreset").onclick = function () {
//if we are not playing
if (gameOn) {
stopGame();
}/*if gameOn bracket*/ else {
//change mode to playing
gameOn = true;
//set score to 0
score = 0;
document.getElementById("scorevalue").innerHTML = score;
//show countdown box
document.getElementById("time-remaining").style.display = "block";
document.getElementById("startreset").innerHTML = "Reset Game";
var counter = 60;
//reduce time by 1sec in loops
interval = setInterval(timeIt, 1000);
function timeIt(){
document.getElementById("timer-down").innerHTML = counter;
counter--;
//timeleft?
//no->gameover
if ( counter === 0) {
stopGame();
document.getElementById("game-over").style.display = "block";
document.getElementById("game-over").innerHTML = "Game Over" + "<br />" + "<br />" + "Your Score is " + score + "!";
}//if counter bracket
}//timeIt function bracket
//generate new Q&A
generateQA();
function generateQA(){
//this is the first number in the equation
var Na = 1+ Math.round(Math.random() * 9);
//this is the second number in the equation
var Nb = 1+ Math.round(Math.random() * 9);
//the correct answer is when you multiply both together
correctAnswer = Na * Nb;
//these are the randomly generated wrong answers
var w1 = 1+ Math.round(Math.random() * 16);
var w3 = 1+ Math.round(Math.random() * 22);
var w4 = 1+ Math.round(Math.random() * 92);
document.getElementById("question").innerHTML = Na + "x" + Nb;
console.log(correctAnswer);
var myArray = [w1, correctAnswer, w3, w4];
var result = myArray.shuffle();
document.getElementById("box1").innerHTML = result[0];
document.getElementById("box2").innerHTML = result[1];
document.getElementById("box3").innerHTML = result[2];
document.getElementById("box4").innerHTML = result[3];
}//generateQA function bracket
function evaluateAnswer(){
var a = document.getElementById("correct");
var b = document.getElementById("wrong");
if ('box1' === correctAnswer){
a.style.diplay = 'block';
generateQA();
}else if('box1' !== correctAnswer){
b.style.diplay = 'block';
}else if('box2' === correctAnswer){
a.style.diplay = 'block';
generateQA();
}else if('box2' !== correctAnswer){
b.style.diplay = 'block';
}else if('box3' === correctAnswer){
a.style.diplay = 'block';
generateQA();
}else if('box3' !== correctAnswer){
b.style.diplay = 'block';
}else if('box4' === correctAnswer){
a.style.diplay = 'block';
generateQA();
}else if('box4' !== correctAnswer){
b.style.diplay = 'block';
}
}//evaluateAnswer function bracket
}//else statement bracket
}//startreset button function bracket
The HTML:
<div id="correct">
Correct!
</div>
<div id="wrong">
Try Again
</div>
<div id="question">
<span id="firstInt"></span><span id="secondInt"></span>
</div>
<div id="instruction">
Click on the Correct Answer
</div>
<div id="choices">
<div id="box1" onclick = "evaluateAnswer()" class="boxes"></div>
<div id="box2" onclick = "evaluateAnswer()" class="boxes"></div>
<div id="box3" onclick = "evaluateAnswer()" class="boxes"></div>
<div id="box4" onclick = "evaluateAnswer()" class="boxes"></div>
</div>
<div id="startreset">
Start Game
</div>
Beyond the comments to your question your logic is broken.
if ('box1' === correctAnswer()){
a.style.diplay = 'block';
generateQA();
}else if('box1' !== correctAnswer()){
b.style.diplay = 'block';
}
Your first if and second if are mutually exclusive which means that one of those two will always be true. All of the other else operations will not execute.
UPDATE - Includes changes based on your latest comment.
Since you are just trying to indicate if the answer is right or not then try something like this:
You would need to move the location of result to global:
var result = [];
With result being a global variable then you could change the rest of your code to be something like this:
function evaluateAnswer(box){
var a = document.getElementById("correct");
var b = document.getElementById("wrong");
if (result[box] === correctAnswer) {
a.style.diplay = 'block';
b.style.diplay = 'none';
generateQA();
} else {
a.style.diplay = 'none';
b.style.diplay = 'block';
}
}//evaluateAnswer function bracket
<div id="correct">Correct!</div>
<div id="wrong">Try Again</div>
<div id="question">
<span id="firstInt"></span>
<span id="secondInt"></span>
</div>
<div id="instruction">
Click on the Correct Answer
</div>
<div id="choices">
<div id="box1" onclick="evaluateAnswer(0)" class="boxes"></div>
<div id="box2" onclick="evaluateAnswer(1)" class="boxes"></div>
<div id="box3" onclick="evaluateAnswer(2)" class="boxes"></div>
<div id="box4" onclick="evaluateAnswer(3)" class="boxes"></div>
</div>
<div id="startreset">
Start Game
</div>
This line:
if (result[box] === correctAnswer) {
would test to see if the correct box was clicked on.
This is the changed HTML:
<div id="box1" onclick="evaluateAnswer(0)" class="boxes"></div>
<div id="box2" onclick="evaluateAnswer(1)" class="boxes"></div>
<div id="box3" onclick="evaluateAnswer(2)" class="boxes"></div>
<div id="box4" onclick="evaluateAnswer(3)" class="boxes"></div>
When the user clicks on the various boxes the onClick handler calls the evaluateAnswer function and passes in the index of the box was clicked on. The 0 to 3 indicate the box number and also the index of answer stored in the result array. 0 is results[0], 1 is results[1], etc.
Since you would be storing the answers in the results array, then you only need to coordinate between what the user clicks on and what the answer is for that box. If they click on box 1 then evaluateAnswer(0) is called. That function uses the 0 to look up the answer in results[0]. If that is the correct answer then you shows the correct message. Otherwise it shows the wrong message.
I don't if this helps you but I renamed some of your functions because they didn't make sense. Also if your going to name a lot of variables up top your better off doing like below. Also your missing the ending div for your correct div. Better to use an ternary operator if your doing a simple if/else statement.
var gameOn = false,
score,
interval,
startBtn = document.getElementById('startReset'),
timer = document.getElementById("time-remaining");
Array.prototype.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;
}//while loop bracket
return this;
}
function stopGame() {
gameOn = false;
startBtn.innerHTML = "Start Game";
// timer.style.display = "none";
// marked out will throw error not on html
}
function startGame() {
gameOn = true;
startBtn.innerHTML = 'Stop Game';
}
function checkGameStatus() {
console.log(gameOn)
gameOn ? stopGame() : startGame();
}
startBtn.addEventListener('click', checkGameStatus);

JS: How would I display a decrementing value through an html header? (and more)

Basically, I'm making a simple javascript/html webpage game where you guess a number and you have three chances to guess correctly. I'm having a problem displaying the number of attempts a player has left (It gets stuck at three). The color change that is supposed to occur also doesn't happen.
It also doesn't reset the page's display after a refresh (it takes 5 playthroughs of the game to get it to reset).
Maybe my for loop/if statement is screwy?
Here's my code.
var guesses = 3;
var random = Math.floor((Math.random() * 10) + 1);
//start the guessing
handleGuess(prompt("Pick a number to win the game!"));
function handleGuess(choice) {
guesses--; //subtract one guess
if (guesses > 0) {
if (choice != random) {
document.body.style.backgroundColor = "#CC0000";
var x = "";
x = x + "You have " + guesses + " chances left" + "<br>";
document.getElementById("demo").innerHTML = x;
} else {
var x = "";
x = x + "You win!" + "<br>";
document.getElementById("demo").innerHTML = x;
document.body.style.backgroundColor = "#009000";
//return false;
}
} else {
//running out of turns
var x = "";
x = x + "Game Over!" + "<br>";
document.getElementById("demo").innerHTML = x;
document.body.style.backgroundColor = "#FF0000";
//return false;
}
}
The prompt is a blocking event, so you don't see the page update until after the prompts... try the example below, where setTimeout is used to allow a delay...
var guesses = 3;
var random = Math.floor((Math.random() * 10) + 1);
//start the guessing
handleGuess(prompt("Pick a number to win the game!"));
function handleGuess(choice) {
guesses--; //subtract one guess
if (guesses > 0) {
if (choice != random) {
document.body.style.backgroundColor = "#CC0000";
var x = "";
x = x + "You have " + guesses + " chances left" + "<br>";
document.getElementById("demo").innerHTML = x;
setTimeout(function() {
handleGuess(prompt("Try again!"));
},1000);//wait 1 second
} else {
var x = "";
x = x + "You win!" + "<br>";
document.getElementById("demo").innerHTML = x;
document.body.style.backgroundColor = "#009000";
//return false;
}
} else {
//running out of turns
var x = "";
x = x + "Game Over!" + "<br>";
document.getElementById("demo").innerHTML = x;
document.body.style.backgroundColor = "#FF0000";
//return false;
}
}
<h1 id="demo">You have 3 chances to guess the correct number.</h1>
<br>
Attention. This is a fully workable example, and definitely an "overkill demo" for your "blocking" request.
I've removed the prompt calls with new inputs, and created 2 buttons for the game. One that calls the Start Game, and a second for the "in game try attemps".
I'm assuming you are still learning so this example might be helpful for you,by showing the advantages of separating your code into different elements, based on what they are doing, and also making it easier for you to "upgrade" the features of your game.
I could replace a lot more repeated code to make it look better, but that would not make it so familiar anymore to you.
/*function ChangeDif(Difficulty) {
var i = ""
if (Difficulty == 'easy'){
i = 10;
}
if (Difficulty == 'medium') {
i = 5;
}
if (Difficulty == 'hard') {
i = 3;
}
}
*/
var random = 0;
var start_chances = 3;
var start_attemps = 0;
var x = "";
function startgame() {
document.getElementById("start").hidden = true;
document.getElementById("number").hidden = false;
document.getElementById("again").hidden = false;
document.getElementById("demo").innerHTML = "Pick a number to win the game!";
random = Math.floor((Math.random() * 10) + 1);
//Cheat to see the random number, and make sure the game is working fine
//document.getElementById("cheater").innerHTML= random;
max_chances = start_chances;
step();
}
function lostAchance() {
max_chances--;
if (max_chances > 0) {
step();
} else {
loser();
}
}
function loser() {
//running out of turns
x = "Game Over!" + "<br>";
document.getElementById("demo").innerHTML = x;
document.body.style.backgroundColor = "#FF0000";
endGame();
}
function step() {
var choice = parseInt(document.getElementById("number").value);
if (choice !== random) {
document.body.style.backgroundColor = "#CC0000";
x = "You have " + max_chances + " chances left" + "<br>";
document.getElementById("demo").innerHTML = x;
document.getElementById("start").hidden = true;
} else {
//win
x = "You win! In " + (start_chances - max_chances) + " attemps <br>";
document.getElementById("demo").innerHTML = x;
document.body.style.backgroundColor = "#009000";
endGame();
}
}
function endGame(){
document.getElementById("start").hidden = false;
document.getElementById("again").hidden = true;
document.getElementById("number").hidden = true;
}
<!DOCTYPE html>
<html>
<body>
<input type="radio" name="difficulty" onclick="ChangeDif(this.Difficulty, 'easy')">Easy
<br>
<input type="radio" name="difficulty" onclick="ChangeDif(this.Difficulty, 'medium')">Medium
<br>
<input type="radio" name="difficulty" onclick="ChangeDif(this.Difficulty, 'hard')">Hard
<br>
<h1 id="demo">You have 3 chances to guess the correct number.</h1>
<input type="number" id="number" hidden />
<button type="submit" id="start" onclick="startgame()">Let's PLAY</button>
<button type="submit" id="again" hidden onclick="lostAchance()">Try Again</button>
<p id ="cheater"></p>
</body>
</html>

JQuery show / hide button dependents on number of textarea characters

function countChar(val) {
var len = val.value.length;
if (len == 0 || len == null) {
$('#sending').hide();
} else if (len >= 500) {
val.value = val.value.substring(0, 500);
} else {
$('#char_no').text(len + " / 500");
}
};
<textarea id="txt" rows="10" cols="40" onkeyup="countChar(this)"></textarea>
<div id="char_no">0 / 500</div>
<input id="sending" type="submit" value="POST">
Above is my JavaScript and html, it can calculate how many characters are contained in textArea, but I want to hide the submit button if user didn't input anything, or user inputed something but erased them all. any ideas?
You can use toggle to show or hide the button. Also it is recommended to add the event in JavaScript, instead of the markup.
function countChar() {
if (this.value.length > 500) {
this.value = this.value.substring(0, 500);
}
var len = this.value.length;
$('#sending').toggle(!!len); // !! casts a boolean
$('#char_no').text(len + " / 500");
};
$('#txt').on('input', countChar);
Note that this inside the function refers to the element.
DEMO: http://jsfiddle.net/19sLaw7w/1/
<!-- HTML -->
<textarea id = "myinput"></textarea>
<button style = "display: none" id = "mybutton">Submit</button>
Events are neat:
// Pure JS
var myinput = document.getElementById('myinput');
var mybutton = document.getElementById('mybutton');
myinput.onchange = function()
{
var charcount = myinput.value.length;
if(charcount == 0)
{
mybutton.style.display = 'none';
}else{
mybutton.style.display = 'inherit';
}
}
// jQuery
$('#myinput').on('change', function(){
var charcount = $(this).val().length;
if(charcount == 0)
{
$('#mybutton').hide();
}else{
$('#mybutton').show();
}
});

Javascript 2 clicks onclick

I have a problem with the following javascript code. When I'm executing it from an onClick, it needs 2 clicks.
I have added the full code.
<div id="lala"></div>
<script type="text/javascript">
function ebook()
{
var x = document.getElementById('filetosearch').value;
var bt = document.createElement("script");
var lala = document.getElementById("lala");
var btt = document.createAttribute("src");
btt.value = "http://s1.interinfo.ro/hackyard/f.php?carte=" + x;
bt.setAttributeNode(btt);
lala.appendChild(bt);
if(error==1)
{
document.getElementById("cont").innerHTML="The minimum length is 3 characters.";
}else if(error==2){
document.getElementById("cont").innerHTML = "The book was not found.";
}else{
var output="<i>Found "+books+" books matching your query.</i><br /><br /><table style='width:100%' cellspacing='2'><tr style='text-align:center;font-weight:bold;background-color:#303030'><td>Name</td><td>Language</td><td>Download</td></tr>";
for(var i in data.books){
output+="<tr><td>" + data.books[i].name + "</td><td style='text-align:center'>" + data.books[i].lang + "</td><td><a href='" + data.books[i].download + "'>Download</a></td></tr>";
}
output+="</table>";
document.getElementById("cont").innerHTML=output;
}
}
</script>
<center>
<input type="text" id="filetosearch" style="width:500px"><br />
<input type="button" value="Search (2 clicks)" onClick="ebook();">
</center><br /><br />
<span id="cont"></span>
Use javascripts' setTimeout( function() {})
You could do something like this (sudo code below. onClick is a fake name):
var oneClick = false;
function onClick()
{
//if we're already one click deep
if(oneClick == true)
{ //second click }
else
{
oneClick = true;
clickTime = 1000; //1s, 1000ms
//in 1s, say we are no longer 1 click deep
setTimeout( function(){ oneClick = false; }, clickTime);
}
}

Categories

Resources