why wont my else if statements work - javascript

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

Related

Evaluate if statements in javascript

So I'm following the modern JavaScript from the beginning by brad traversy, and in the guess number project the app ignores all the conditions in the first if statement and continue. I checked the code in the project file and it's the same, I tried switch statement, I put each condition in a separate if statement, and still doesn't work
let min = 1,
max = 10,
winningGuess = 2,
guessesNum = 3;
// Grab on UI Elements
const game = document.querySelector('#game'),
minNum = document.querySelector('.min-num'),
maxNum = document.querySelector('.max-num'),
guessInput = document.querySelector('#guess-input'),
guessBtn = document.querySelector('#guess-btn'),
message = document.querySelector('.message');
// Assign UI to min and Max
minNum.textContent = min;
maxNum.textContent = max;
// Add an EventListener
guessBtn.addEventListener('click', function() {
let guess = parseInt(guessInput.value);
if (isNaN(guess) || guess < min || guess > max) {
setMessage(`Please enter a Number between ${min} and ${max}`);
}
if (guess === winningGuess) {
gameOver(true, `Great Job ${winningGuess} is the Correct guess, You Won!`)
} else {
guessesNum -= 1;
if (guessesNum === 0) {
gameOver(false, `Sorry you lost, The correct guess was ${winningGuess}`)
} else {
guessInput.style.borderColor = 'red';
setMessage(`${guess} is not the correct number, You have ${guessesNum} guesses left. Please try again`, 'red');
guessInput = '';
}
}
});
function gameOver(won, msg) {
let color;
won === true ? color = 'green' : color = 'red';
guessInput.disabled = true;
guessInput.style.borderColor = color;
message.style.color = color;
setMessage(msg);
}
function setMessage(msg, color) {
message.textContent = msg;
message.style.color = color;
};
<div class="container">
<h1>The Number Guesser Game</h1>
<div id="game">
<p>Guess a number between <span class="min-num"></span> and <span class="max-num"></span></p>
<input type="number" id="guess-input" placeholder="Enter Your Guess">
<input type="submit" value="Submit" id="guess-btn">
<p class="message"></p>
</div>
</div>
Your if statement is absolutely fine, the reason you never see the message "Please enter a Number between ${min} and ${max}" is because you let the code continue, and almost immediately that message is overwritten by a different one. Simply adding a return statement within your if block will solve this problem.
Note I also fixed this line guessInput = ''; which should be guessInput.value = '';
let min = 1,
max = 10,
winningGuess = 2,
guessesNum = 3;
// Grab on UI Elements
const game = document.querySelector('#game'),
minNum = document.querySelector('.min-num'),
maxNum = document.querySelector('.max-num'),
guessInput = document.querySelector('#guess-input'),
guessBtn = document.querySelector('#guess-btn'),
message = document.querySelector('.message');
// Assign UI to min and Max
minNum.textContent = min;
maxNum.textContent = max;
// Add an EventListener
guessBtn.addEventListener('click', function() {
let guess = parseInt(guessInput.value);
if (isNaN(guess) || guess < min || guess > max) {
setMessage(`Please enter a Number between ${min} and ${max}`);
return; // here
}
if (guess === winningGuess) {
gameOver(true, `Great Job ${winningGuess} is the Correct guess, You Won!`)
} else {
guessesNum -= 1;
if (guessesNum === 0) {
gameOver(false, `Sorry you lost, The correct guess was ${winningGuess}`)
} else {
guessInput.style.borderColor = 'red';
setMessage(`${guess} is not the correct number, You have ${guessesNum} guesses left. Please try again`, 'red');
guessInput.value = '';
}
}
});
function gameOver(won, msg) {
let color;
won === true ? color = 'green' : color = 'red';
guessInput.disabled = true;
guessInput.style.borderColor = color;
message.style.color = color;
setMessage(msg);
}
function setMessage(msg, color) {
message.textContent = msg;
message.style.color = color;
};
<div class="container">
<h1>The Number Guesser Game</h1>
<div id="game">
<p>Guess a number between <span class="min-num"></span> and <span class="max-num"></span></p>
<input type="number" id="guess-input" placeholder="Enter Your Guess">
<input type="submit" value="Submit" id="guess-btn">
<p class="message"></p>
</div>
</div>
Try changing the const to let. You're editing all these later in your code:
let game = document.querySelector('#game'),
minNum = document.querySelector('.min-num'),
maxNum = document.querySelector('.max-num'),
guessInput = document.querySelector('#guess-input'),
guessBtn = document.querySelector('#guess-btn'),
message = document.querySelector('.message');

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>

Global variable in number guessing game

I'm trying to make the standard number guessing game that MDN provides in their JS tutorial. I tried tweaking it a bit making different functions for the different scenarios.
It seems the global variable var userGuess = parseInt(guessField.value) is not working as your previous guess always comes up as NaN.
Also when the game resets the showWin() and showLoss() functions work but not the showError() function.
I am very new to JS and coding in general so there is most likely a silly mistake somewhere, if anyone could help me on this problem, that would be greatly appreciated!
var randNum = Math.floor(Math.random() * 100) + 1;
var guessField = document.querySelector('.guessField');
var guessSubmit = document.querySelector('.guessSubmit');
var guesses = document.querySelector('.guesses');
var lastResult = document.querySelector('.lastResult');
var lowOrHi = document.querySelector('.lowOrHi');
var guessCount = 1;
var resetButton;
var userGuess = parseInt(guessField.value);
function checkGuess() {
if(guessCount === 1) {
guesses.textContent = "Previous Guesses: ";
}
guesses.textContent += userGuess + ' ';
if(userGuess === randNum) {
showWin();
} else if(guessCount === 10) {
showLoss();
} else {
showError();
}
guessCount++;
guessField.value = '';
guessField.focus();
}
guessSubmit.addEventListener('click', checkGuess);
function showWin() {
lastResult.textContent = 'You won nice job schmuck';
lastResult.style.backgroundColor = 'green';
gameOver();
}
function showError() {
lastResult.textContent = 'Sorry, wrong guess';
if(userGuess > randNum) {
lowOrHi.textContent = 'Your guess was too high';
} else if(userGuess < randNum) {
lowOrHi.textContent = 'Your guess was too low';
}
}
function showLoss() {
lastResult.textContent = 'You lost, you schmuck';
lastResult.style.backgroundColor = 'red';
gameOver();
}
function gameOver() {
guessField.disabled = true;
guessSubmit.disabled = true;
resetButton = document.createElement('button');
resetButton.textContent = 'New Game';
document.body.appendChild(resetButton);
resetButton.addEventListener('click', resetGame);
}
function resetGame() {
guessCount = 1;
var resetParas = document.querySelectorAll('.resultParas');
for(i = 0; i < resetParas.length; i++) {
resetParas[i].textContent = '';
}
guessField.disabled = false;
guessSubmit.disabled = false;
resetButton.parentNode.removeChild(resetButton);
lastResult.style.backgroundColor = 'white';
randNum = Math.floor(Math.random() * 100) + 1;
}
<h1>Guessing Game</h1>
<p>Type in a number between 1 and 100 and I will tell you if it is too high or low.</p>
<form>
<label for="guessField">Enter a guess: </label>
<input type="text" id="guessField" class="guessField"/>
<input type="button" value="Submit Guess" class="guessSubmit"/>
</form>
<div class='resultParas'>
<p class="guesses"></p>
<p class="lastResult"></p>
<p class="lowOrHi"></p>
</div>
In your script, you call
parseInt(guessField.value) // effectively that is parseInt("") when it's empty
Calling parseInt() with an empty string returns NaN;
MDN in their example use:
var userGuess = Number(guessField.value);
Number("") returns a 0 number value.
You would also need to update the value of userGuess every time you call checkGuess(). So the alterations you need are:
// ... code
var userGuess = Number(guessField.value);
// ... the rest of code
function checkGuess() {
userGuess = Number(guessField.value)
// ... rest of code
}
// rest of code
You don't have to use Number() of course, you could also do some other condition checking, but Number() is an elegant way of accepting either numbers or an empty string.
UPDATE
New jsbin here.
For the resetGame() part: you were selecting the .resultParas like:
var resetParas = document.querySelectorAll('.resultParas');
Then you iterated over the results of that and replaced the .textContent of those elements. But those were not simple text nodes, they were parapgraph nodes with text nodes inside them. I changed it to:
var resetParas = document.querySelector('.resultParas').children;
It should be working! I've put some comments in the jsfiddle for more explanation.

how can i put my randomized answer placement in different divs...Read Post

I'm currently making a simple math game where it generates random multiplication problems and there is multiple choices that the user can pick from. Right now I am getting stuck on how to place my shuffled answers into separate divs for the multiple choices. Also if you notice any collisions that may arise in the future a heads up would be greatly appreciated
Here's 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", "box2", "box3", "box4").innerHTML = result;
}//generateQA function bracket
}//else statement bracket
}//startreset button function bracket
Here's the HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Math Game</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes">
<link rel="stylesheet" href="styling.css">
</head>
<body>
<div id="title">
The Matheroo
</div>
<div id="sunYellow">
<!--Because the score value is going to change as the user plays the game we need to place it in a span and refer to it later with some JAVA-->
<div id="score">
Score: <span id="scorevalue">0</span>
</div>
<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" class="boxes"></div>
<div id="box2" class="boxes"></div>
<div id="box3" class="boxes"></div>
<div id="box4" class="boxes"></div>
</div>
<div id="startreset">
Start Game
</div>
<div id="time-remaining">
Time Remaining: <span id="timer-down">60</span> sec
</div>
<div id="game-over">
<br />
Game Over
</div>
</div>
<script src="Javascript.js"></script>
</body>
</html>
You can't select multiple elements with getElementById as you did in this line document.getElementById("box1", "box2", "box3", "box4").innerHTML = result;. Selecting multiple elements will be done with querySelectorAll.
But for your case, just do it this way:
document.getElementById("box1").innerHTML = result[0];
document.getElementById("box2").innerHTML = result[1];
document.getElementById("box3").innerHTML = result[2];
document.getElementById("box4").innerHTML = result[3];
You can also do it with a for loop.

Javascript: Loop items in array

For my website I need a function with questions and answers in loop.
After the last question the first question should come again.
I have found something but the loop does not work, it is certainly simple but I do not get that.
<!DOCTYPE html>
<html>
<body>
<div>
<div id="question" onclick="changeText()">
Start Quiz
</div>
<div id="answer" onclick="nextQuestion()">
are you ready?
</div>
</div>
<script type="text/javascript">
var details = "Question 1ans:Answer 1qst:Question 2ans:Answer 2qst:Question 3ans:Answer 3qst:Question 4ans:Answer 4qst:Question 5ans:Answer 5qst:Question 6ans:Answer 6qst:Question 7ans:Answer 7qst:Question 8ans:Answer 8qst:Question 9ans:Answer 9qst:Question 10ans:Answer 10";
var questionList = details.split("qst:");
var div = document.getElementById('question');
var ans = document.getElementById('answer');
function changeText(){
if (div.style.display !== 'none') {
div.style.display = 'none';
ans.style.display = 'block';
}
else {
div.style.display = 'block';
ans.style.display = 'none';
}
}
function nextQuestion(){
div.style.display = 'block';
ans.style.display = 'none';
var max = questionList.length;
if(max > 0){
var num = 0;
var qst = questionList[num].split("ans:");
div.innerHTML =qst[0];
ans.innerHTML = qst[1];
questionList.splice(num,1);}
else {
}
}
</script>
</body>
</html>
You must reset value of n every time reach to max so you must put n in outer scope in global variable scope and don't splice questionList because you want to iterate over that array again after reaching to end of it:
var details = "Question 1ans:Answer 1qst:Question 2ans:Answer 2qst:Question 3ans:Answer 3qst:Question 4ans:Answer 4qst:Question 5ans:Answer 5qst:Question 6ans:Answer 6qst:Question 7ans:Answer 7qst:Question 8ans:Answer 8qst:Question 9ans:Answer 9qst:Question 10ans:Answer 10";
var questionList = details.split("qst:");
var div = document.getElementById('question');
var ans = document.getElementById('answer');
//Variable n must declare here
var num = 0;
function changeText() {
if (div.style.display !== 'none') {
div.style.display = 'none';
ans.style.display = 'block';
} else {
div.style.display = 'block';
ans.style.display = 'none';
}
}
function nextQuestion() {
div.style.display = 'block';
ans.style.display = 'none';
var max = questionList.length;
if (max > 0) {
var qst = questionList[num].split("ans:");
div.innerHTML = qst[0];
ans.innerHTML = qst[1];
//there is no need to splice questionList
//questionList.splice(num, 1);
num++;
//Check for num to not to be greater than questionList.length
if (num >= max)
num = 0;
} else {
}
}
<div id="question" onclick="changeText()">
Start Quiz
</div>
<div id="answer" onclick="nextQuestion()">
are you ready?
</div>

Categories

Resources