Changing image while clicking button in html/javascript - 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>

Related

Need To stop Timer counting down when browser tab minimized or been switched between tabs

Here is my script written
I want to stop timer when user switch to different tabs and resume back when visit the site. can anyone help me to solve this task. Need To stop Timer counting down when browser tab focus or been switched between tabs can
anyone help me to this code
<div style="text-align: center;">
<a class="button" href="" id="download">Click To Download</a>
<button class="infoblogger" id="btn"> Download</button>
<script>
var downloadButton = document.getElementById("download");
var counter = 45;
var newElement = document.createElement("p");
newElement.innerHTML = "www.xyz.com";
var id;
downloadButton.parentNode.replaceChild(newElement, downloadButton)
function startDownload() {
this.style.display = 'none';
id = setInterval(function() {
counter--;
if (counter < 0) {
newElement.parentNode.replaceChild(downloadButton, newElement);
clearInterval(id);
} else {
newElement.innerHTML = +counter.toString() + " second.Please Wait";
}
}, 1000);
};
var clickbtn = document.getElementById("btn");
clickbtn.onclick = startDownload
</script>
</div>
1st : <script> tag is not used inside div element
2nd : You can use a extra variable and check its state to run the function.
Here used focusOut whose value is false, and value changes to true if window minimizes or out of focus(other tab opened) and change back to false if gains back the focus. This state is used to keep the function running.
var downloadButton = document.getElementById("download");
var counter = 45;
var newElement = document.createElement("p");
newElement.innerHTML = "www.xyz.com";
var id;
let focusOut = false;
downloadButton.parentNode.replaceChild(newElement, downloadButton)
function startDownload() {
this.style.display = 'none';
id = setInterval(function() {
if (!focusOut) {
counter--;
if (counter < 0) {
newElement.parentNode.replaceChild(downloadButton, newElement);
clearInterval(id);
} else {
newElement.innerHTML = +counter.toString() + " second.Please Wait";
}
}
}, 1000);
};
var clickbtn = document.getElementById("btn");
clickbtn.onclick = startDownload
window.addEventListener('blur', function() {
focusOut = true;
})
window.addEventListener('focus', function() {
focusOut = false;
});
<div style="text-align: center;">
<a class="button" href="" id="download">Click To Download</a>
<button class="infoblogger" id="btn"> Download</button>
</div>
<script>
</script>

Having trouble with displaying an image through an array

I am practicing with JavaScript Array function. What I want to achieve is to show google embedded images inside the display section when the user clicks "Show my grocery list" button after entering "banana", else the texts will be shown instead.
These are my codes.
var grocery = document.getElementById("grocery");
let showItems = document.getElementById("showItems");
const display = document.getElementById("display");
var groceryList = [];
grocery.addEventListener("keyup",function(ev){
if(ev.keyCode == 13){
groceryList.push(grocery.value);
console.log("array",groceryList);
}
});
showItems.addEventListener("click",function(){
for (var i = 0; i < groceryList.length;i++){
if(groceryList[i] == "banana"){
display.src = "https://i5.walmartimages.ca/images/Enlarge/271/747/6000191271747.jpg";
} else {
display.innerHTML += groceryList[i] + "<br/>";
}
}
});
#display {
width:100px;
height:100px;
}
<div id="controls">
<input type="text" placeholder="grocery items" id="grocery"/>
<button id="showItems">Show My Grocery List</button>
</div>
<div id="display"></div>
It is currently not showing anything. I have a feeling that I have written a wrong syntax inside the loop function? I would appreciate a solution and tips. Thank you.
You've to remove the keyCode=13 condition first and then need to create an img element with src of image based on condition (groceryList[i] == "banana") to display the image inside the <div> element, For example:
var grocery = document.getElementById("grocery");
let showItems = document.getElementById("showItems");
const display = document.getElementById("display");
var groceryList = [];
grocery.addEventListener("keyup", function(ev) {
//if(ev.keyCode == 13){
groceryList.push(grocery.value);
//console.log("array",groceryList);
//}
});
showItems.addEventListener("click", function() {
for (var i = 0; i < groceryList.length; i++) {
if (groceryList[i] == "banana") {
var source = "https://i5.walmartimages.ca/images/Enlarge/271/747/6000191271747.jpg";
var img = document.createElement("IMG"); //create img element
img.src = source; //set img src
display.appendChild(img); // display image inside <div>
} else {
display.innerHTML += groceryList[i] + "<br/>";
}
}
});
<div id="controls">
<input type="text" placeholder="grocery items" id="grocery" />
<button id="showItems">Show My Grocery List</button>
</div>
<div id="display"></div>

Personal Best Scorekeeper / Timer

I'm making a timer that records the longest time (personal best) when clicking 'ok' on the pass button. I can't seem to figure out how to get the counter back to 0 and I'm sure there's a way to do it with only 2 buttons (start + pass). I want the timer to start again when I press start, at the moment it just runs each case once and returns the highest value. The timer currently logs the second after the number shown on screen which I do not understand.
Thanks in advance for your help, much appreciated!
var c = 0;
var d = 0;
var pb;
function myCounter() {
document.getElementById("demo").innerHTML = c++;
}
function restartCount() {
document.getElementById("demo").innerHTML = d++;
}
function userPass() {
if (confirm("Are you sure?")) {
console.log(c,d);
clearInterval(myCounter);
clearInterval(restartCount);
document.getElementById("personalBest").innerHTML = Math.max(c,d);
} else {
document.getElementById("good").innerHTML = "Keep it up!";
}
}
<h1>Best Time = <span id="personalBest"></span></h1>
<p id="good"></p>
<p id="demo"></p>
<button onClick="myCounter = setInterval(myCounter, 1000)">Start counter!</button>
<button onclick="userPass()">Pass</button>
<button onclick="restartCount = setInterval(restartCount, 1000)">Restart</button>
Regarding your second question "The timer currently logs the second after the number shown on screen which I do not understand."
This is linked to where you put the ++ in this line
document.getElementById("demo").innerHTML = c++;
c++ means get the value of c then increment it. I believe you want to increment first (because 1 second has elapse) then assign and use.
In this case you should use ++c instead.
document.getElementById("demo").innerHTML = ++c;
There were a few mistakes
timer variable name and function variable name were same, they need to be different. Also, it is cleaner to invoke a simple method rather than starting timer from the onclick.
No need for second start button, ensure that you clear c and timer before starting new timer.
var c = 0;
var d = 0;
var myCounter;
function myCounter1() {
c = 0; //set c to 0;
clearInterval(myCounter);
myCounter = setInterval(() => {
document.getElementById("demo").innerHTML = c++;
}, 1000);
}
function userPass() {
if (confirm("Are you sure?")) {
d = Math.max(c,d);
clearInterval(myCounter);
document.getElementById("personalBest").innerHTML = d;
} else {
document.getElementById("good").innerHTML = "Keep it up!";
}
}
<h1>Best Time = <span id="personalBest"></span></h1>
<p id="good"></p>
<p id="demo"></p>
<button onClick="myCounter1()">Start counter!</button>
<button onclick="userPass()">Pass</button>

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

Trying to display image in a game of memory

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

Categories

Resources