Images wont change HTML - javascript

It's been a while since I've used html and am trying to make a simple dice rolling website. However, the images don't change in the text file, after I press the designated button. I've tried everything I could think of, and have spent 5+ hours trying to figure out why it does work.
<html>
<h1>Dice roller</h1>
<p>Roll a dice to recieve a reward base on your roll.</p>
<script>
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
var dieroll = 0;
function roll(){
var image = document.getElementById("dice");
dieroll = getRandomInt(1,6);
document.getElementById("result").innerHTML = dieroll;
if (dieroll==1){
image.src="1die.jpg";
} else {
if (dieroll ==2){
image.src="2die.jpg";
}
} else {
if (dieroll==3){
image.src="3die.jpg";
}
} else {
if (dieroll==4){
image.src="4die.jpg";
}
} else {
if (dieroll==5){
image.src="5die.jpg";
}
} else {
if (dieroll==6){
image.src="6die.jpg";
}
}
}
</script>
<body>
<button onclick="roll()">Click me to roll</button>
</body>
<h2>The value for your roll is: <div id="result"></div></h2>
<div>
<img src="https://th.bing.com/th/id/OIP.a84-UisZ9wZzwQZdXumxTgHaHV?w=174&h=180&c=7&o=5&pid=1.7" id="dice" width="100" height="100">
</div>
</html>
Additionally, the images I'm trying to use file names are entered correctly, and the original image appears just fine, just changing it is what isn't working.

Your if else statements had several errors, here it is fixed.
Other than that you have to make sure the images, such as 4die.jpg, are in the same directory as your html file, otherwise you need to print the full absolute or relative html, for example /images/4die.jpg or images/4die.jpg
<html>
<h1>Dice roller</h1>
<p>Roll a dice to recieve a reward base on your roll.</p>
<script>
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
var dieroll = 0;
function roll(){
var image = document.getElementById("dice");
dieroll = getRandomInt(1,6);
document.getElementById("result").innerHTML = dieroll;
if (dieroll==1){
image.src="1die.jpg";
} else if (dieroll ==2){
image.src="2die.jpg";
} else if (dieroll==3){
image.src="3die.jpg";
} else if (dieroll==4){
image.src="4die.jpg";
} else if (dieroll==5){
image.src="5die.jpg";
} else if (dieroll==6){
image.src="6die.jpg";
}
}
</script>
<body>
<button onclick="roll()">Click me to roll</button>
</body>
<h2>The value for your roll is: <div id="result"></div></h2>
<div>
<img src="https://th.bing.com/th/id/OIP.a84-UisZ9wZzwQZdXumxTgHaHV?w=174&h=180&c=7&o=5&pid=1.7" id="dice" width="100" height="100">
</div>
</html>

The reason why it did not work was because your nested if-else statements were too messed up. Here is a better approach using switch case.
You can inspect to see change in src:
Working snippet :
<html>
<h1>Dice roller</h1>
<p>Roll a dice to recieve a reward base on your roll.</p>
<script>
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
var dieroll = 0;
function roll() {
var image = document.getElementById("dice");
dieroll = getRandomInt(1, 6);
document.getElementById("result").innerHTML = dieroll;
switch (dieroll) {
case 1:
image.src = "1die.jpg";
break;
case 2:
image.src = "2die.jpg";
break;
case 3:
image.src = "3die.jpg";
break;
case 4:
image.src = "4die.jpg";
break;
case 5:
image.src = "5die.jpg";
break;
case 6:
image.src = "6die.jpg";
}
}
</script>
<body>
<button onclick="roll()">Click me to roll</button>
</body>
<h2>The value for your roll is:
<div id="result"></div>
</h2>
<div>
<img src="https://th.bing.com/th/id/OIP.a84-UisZ9wZzwQZdXumxTgHaHV?w=174&h=180&c=7&o=5&pid=1.7" id="dice" width="100" height="100">
</div>
</html>

Well, it should have been a very, very long time since you last worked with HTML/javascript. Your code is well written programatically, but doesn't work due to several syntax errors.
To start with, you have some elements outside of the <body> elements. Moving to the javascript, you cannot have an else statement, unless it is preceded by either an if or else if statement. Instead of
if (condition1) {
// do something
} else {
if(condition2) {
// do something else
}
}
you need to use
if (condition1) {
// do something
} else if(condition2) {
// do something else
}
After applying these fixes, your code works as it should:
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
var dieroll = 0;
function roll() {
var image = document.getElementById("dice");
dieroll = getRandomInt(1, 6);
document.getElementById("result").innerHTML = dieroll;
if (dieroll == 1) {
image.src = "1die.jpg";
} else if (dieroll == 2) {
image.src = "2die.jpg";
} else if (dieroll == 3) {
image.src = "3die.jpg";
} else if (dieroll == 4) {
image.src = "4die.jpg";
} else if (dieroll == 5) {
image.src = "5die.jpg";
} else if (dieroll == 6) {
image.src = "6die.jpg";
}
}
<button onclick="roll()">Click me to roll</button>
<h2>The value for your roll is:
<div id="result"></div>
</h2>
<div>
<img src="https://th.bing.com/th/id/OIP.a84-UisZ9wZzwQZdXumxTgHaHV?w=174&h=180&c=7&o=5&pid=1.7" id="dice" width="100" height="100">
</div>

You have 5 else statements after your initial if statement. You're gonna want to change them to either "if" or "else if" statements and that should do the trick.
FROM:
if(dieroll==1)image.src="1die.jpg";} else {if (dieroll ==2){image.src="2die.jpg";}
TO:
if(dieroll==1){image.src="1die.jpg";}else if (dieroll
==2){image.src="2die.jpg";}
and so on

Related

Creating a javascript function that can check different kinds of arithmetic based on select menu options

I am creating a math game with javascript that asks the user to solve basic math problems based on their chosen select menu option. The user will enter their answer using an input field and when the enter key is pressed a function is called that checks wether or not the answer is correct.
I am having trouble creating a function that can check the different kinds of arithmetic when the enter key is pressed. So far I have only managed to create a check function that can check a single kind of arithmetic.
The basics of the game are this:
the user selects wether to do addition, subtraction, multiplication, or division, then presses the "start" button and the first question is generated of their chosen operation
when the enter key is pressed if the users input is correct, the score is incremented by 1, and a new question of the same kind of arithmetic is generated, if not they are asked to try again.
let gameMenu = document.getElementById('game-menu');
let gameCard = document.getElementById('game-card');
let x = document.getElementById("num1");
let y = document.getElementById("num2");
let displayOperator = document.getElementById('display-operator');
let score = 0;
let answer = document.getElementById('user-answer');
answer.addEventListener('keyup', function(e) {
if (e.key === 'Enter') {
check();
}
});
function start() {
let opt = document.getElementById('opt');
let selOpt = opt.options[opt.selectedIndex].value;
if (selOpt == "+") {
doAddition();
}
if (selOpt == "-") {
doSubtraction();
}
if (selOpt == "*") {
doMultiplication();
}
if (selOpt == "/") {
doDivision();
}
}
function doAddition() {
displayOperator.innerHTML = "&plus;"
x.innerHTML = Math.floor(Math.random() * 5 + 1);
y.innerHTML = Math.floor(Math.random() * 5 + 1);
}
function doSubtraction() {
displayOperator.innerHTML = "−"
x.innerHTML = Math.floor(Math.random() * 5 + 1);
y.innerHTML = Math.floor(Math.random() * 5 + 1);
}
function doMultiplication() {
displayOperator.innerHTML = "×"
x.innerHTML = Math.floor(Math.random() * 5 + 1);
y.innerHTML = Math.floor(Math.random() * 5 + 1);
}
function doDivision() {
displayOperator.innerHTML = "÷"
x.innerHTML = Math.floor(Math.random() * 5 + 1);
y.innerHTML = Math.floor(Math.random() * 5 + 1);
}
function check() {
let x = parseInt(document.getElementById("num1").innerHTML);
let y = parseInt(document.getElementById("num2").innerHTML);
let tryAgain = document.getElementById("try-again");
let answer = parseInt(document.getElementById("user-answer").value);
if (answer === x + y) {
score++;
document.getElementById("score").innerHTML = score;
} else {
tryAgain.innerHTML = "incorrect, try again";
preventDefault();
}
document.getElementById("user-answer").value = "";
doAddition();
}
#question {
display: flex;
flex-direction: row;
}
<!DOCTYPE html>
<head>
</head>
<body>
<div id="game-menu">
<p>game menu</p>
<select id="opt">
<option value="+">Addition</option>
<option value="-">Subtraction</option>
<option value="*">Multiplication</option>
<option value="/">Division</option>
</select>
<button onclick="start()">START</button>
</div>
<div id="game-card">
<div id="question">
<p id="num1"></p>
<p id="display-operator"></p>
<p id="num2"></p>
</div>
<p id="try-again"></p>
<input id="user-answer">
<p id="score">score</p>
</div>
</body>
This is the current code that I have.
I have separate functions for each type of arithmetic and plan on modifying the Math.floor(Math.random()*5+1) in the doSubtraction() and doDivision() functions to prevent negative answers and avoid division questions that aren't evenly divisible.
The problem I'm facing now is that I am not clear on how to make the check() function account for what the user chose from the select menu. I've included (answer === x + y) and doAddition() in the check() function to show how it works, but I cant figure out how to make it check for the proper arithmetic based on the select menu that was chosen, and then call back to the same type of function that was chosen.
I'm pretty new to javascript and appreciate the help and any constructive criticism too. Thanks.
Get the value of the dropdown the same way you do it in start(), then use similar if/else if statements to check the result.
At the end of check() call start() again to generate a new question using the same select option.
You need to clear tryAgain when the user enters a correct answer.
let gameMenu = document.getElementById('game-menu');
let gameCard = document.getElementById('game-card');
let x = document.getElementById("num1");
let y = document.getElementById("num2");
let displayOperator = document.getElementById('display-operator');
let score = 0;
let answer = document.getElementById('user-answer');
answer.addEventListener('keyup', function(e) {
if (e.key === 'Enter') {
check();
}
});
function start() {
let opt = document.getElementById('opt');
let selOpt = opt.options[opt.selectedIndex].value;
if (selOpt == "+") {
doAddition();
}
if (selOpt == "-") {
doSubtraction();
}
if (selOpt == "*") {
doMultiplication();
}
if (selOpt == "/") {
doDivision();
}
}
function doAddition() {
displayOperator.innerHTML = "&plus;"
x.innerHTML = Math.floor(Math.random() * 5 + 1);
y.innerHTML = Math.floor(Math.random() * 5 + 1);
}
function doSubtraction() {
displayOperator.innerHTML = "−"
x.innerHTML = Math.floor(Math.random() * 5 + 1);
y.innerHTML = Math.floor(Math.random() * 5 + 1);
}
function doMultiplication() {
displayOperator.innerHTML = "×"
x.innerHTML = Math.floor(Math.random() * 5 + 1);
y.innerHTML = Math.floor(Math.random() * 5 + 1);
}
function doDivision() {
displayOperator.innerHTML = "÷"
x.innerHTML = Math.floor(Math.random() * 5 + 1);
y.innerHTML = Math.floor(Math.random() * 5 + 1);
}
function check() {
let x = parseInt(document.getElementById("num1").innerHTML);
let y = parseInt(document.getElementById("num2").innerHTML);
let tryAgain = document.getElementById("try-again");
let answer = parseInt(document.getElementById("user-answer").value);
let selOpt = document.getElementById('opt').value;
let correctAnswer;
switch (selOpt) {
case '+': correctAnswer = x + y; break;
case '-': correctAnswer = x - y; break;
case '*': correctAnswer = x * y; break;
case '/': correctAnswer = Math.floor(x / y); break;
}
if (answer === correctAnswer) {
score++;
document.getElementById("score").innerHTML = score;
tryAgain.innerHTML = '';
} else {
tryAgain.innerHTML = "incorrect, try again";
}
document.getElementById("user-answer").value = "";
start();
}
#question {
display: flex;
flex-direction: row;
}
<!DOCTYPE html>
<head>
</head>
<body>
<div id="game-menu">
<p>game menu</p>
<select id="opt">
<option value="+">Addition</option>
<option value="-">Subtraction</option>
<option value="*">Multiplication</option>
<option value="/">Division</option>
</select>
<button onclick="start()">START</button>
</div>
<div id="game-card">
<div id="question">
<p id="num1"></p>
<p id="display-operator"></p>
<p id="num2"></p>
</div>
<p id="try-again"></p>
<input id="user-answer">
<p id="score">score</p>
</div>
</body>
You should probably already store the correct answer once you decide on which arithmetic you are going to ask, and pass it to the check function. Then you'll only have to check if the user's answer is the same as the correct one.

How can I make a math question generator that gives 3 digit addition questions and single digit multiplication questions using JavaScript?

In this code, I am basically trying to create a math question generator, where I want the question generator to randomize between addition subtraction, and multiplication. As of now, I have a code that allows me to create problems that are just single digits, how can I make it so the addition and subtraction questions are 2-3 digits and multiplication is only one digit? (I am new to JavaScript so it is a little bit confusing to me)
I.e. 202+305 = 507
next question
2x4=8
So on and so forth.
Here is the code that I have until now.
<!DOCTYPE html>
<html lang="en">
<body>
<div id="11question"></div>
<input id="answer" />
<button id="check" onclick="check()">Check</button>
</body>
<script>
var operations = {
'+': function (num5, num6) {
return num5 + num6;
},
'-': function (num5, num6) {
return num5 - num6;
},
x: function (num5, num6) {
return num5 * num6;
},
};
var accans;
newquestion();
function newquestion() {
document.getElementById('answer').value = '';
document.getElementById('answer').style.backgroundColor = 'white';
var num5 = Math.floor(Math.random() * 10) + 1;
var num6 = Math.floor(Math.random() * 10) + 1;
var operationChosen = ['+', '-', 'x'][
Math.min(Math.floor(Math.random() * 3))
];
accans = operations[operationChosen](num5, num6);
document.getElementById('11question').innerHTML =
num5 + operationChosen + num6;
}
function check() {
answer = document.getElementById('answer').value;
if (accans == answer) {
document.getElementById('answer').style.backgroundColor = 'green';
setTimeout(newquestion, 1500);
} else if (accans != answer) {
document.getElementById('answer').style.backgroundColor = 'red';
setTimeout(newquestion, 1500);
}
}
</script>
'
</html>
You can define a range by getRandomInt. Check out here
Live Demo:
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min) + min); //The maximum is exclusive and the minimum is inclusive
}
var operations = {
'+': function (num5, num6) {return num5 + num6;},
'-': function (num5, num6) {return num5 - num6;},
'x': function (num5, num6) {return num5 * num6;}
}
var accans
newquestion()
function newquestion() {
document.getElementById('answer').value = "";
document.getElementById('answer').style.backgroundColor = "white";
var operationChosen = ['+','-','x'][Math.min(Math.floor(Math.random()*3))];
if (operationChosen == 'x') {
var num5 = getRandomInt(0,10);
var num6 = getRandomInt(0,10);
}
else {
var num5 = getRandomInt(10,1000);
var num6 = getRandomInt(10,1000);
}
accans = operations[ operationChosen ]( num5, num6 )
document.getElementById("11question").innerHTML = num5 + operationChosen + num6;
}
function check() {
answer = document.getElementById('answer').value;
if (accans == answer) {
document.getElementById('answer').style.backgroundColor = "green";
setTimeout(newquestion, 1500);
}
else if (accans != answer) {
document.getElementById('answer').style.backgroundColor = "red";
setTimeout(newquestion, 1500);
}
}
<div id="11question"></div>
<input id="answer">
<button id="check" onclick="check()">Check</button>

How do I see the console.log in this code?

var hexBeat;
function clarity() {
setInterval(function() {
function randomNumber(min, max) {
return Math.random() * (max - min) + min;
hexBeat = randomNumber(1, 25);
console.log(hexBeat);
}
}, 1000)
}
while (hexBeat <= 20) {
document.querySelector("#nachoCheddar01").style.backgroundColor = "green";
document.querySelector("#nachoCheddar01").style.left = "200px";
}
<html>
<body>
<button onClick="clarity()" style="z-index:1">click for random number in console</button>
<div id="nachoCheddar01" style="z-index: -1; box-sizing:border-box;border:3px solid green;background-color: blue;position:absolute;top:1%;height:100px;width:200px;">NachoCheddar01</div>
<div id="nachoCheddar02" style="">NachoCheddar02</div>
<div id="nachoCheddar03" style="">NachoCheddar03</div>
<div id="nachoCheddar04" style="">NachoCheddar04</div>
</body>
</html>
I am trying to log hexBeat, then based on that I would like to move the rectangle to the right on the screen every time there is a random number less than or equal to 20, and also change its color. But right now I'm failing to get the console.log(hexBeat)
I tried declaring the variable outside of any function. I'm trying to use that variable, hexBeat inside another function, and I have had success declaring my variables like that. Although, I'm using intervals, and I'm not sure if there is a better way to approach moving the rectangle every time there is a random number less than or equal to 20.
You can update your code like this:
HTML:
<html>
<body>
<button onClick="clarity()" style="z-index:1">click for random number in console</button>
<div class="wrapper">
<div id="nachoCheddar01" style="z-index: -1; box-sizing:border-box;border:3px solid green;background-color: blue;position:absolute;top:1%;height:100px;width:200px;">NachoCheddar01</div>
<div id="nachoCheddar02" style="">NachoCheddar02</div>
<div id="nachoCheddar03" style="">NachoCheddar03</div>
<div id="nachoCheddar04" style="">NachoCheddar04</div>
</div>
</body>
</html>
CSS:
.wrapper {
position: relative;
}
#nachoCheddar01 {
position: absolute;
}
JAVASCRIPT:
var hexBeat;
function clarity() {
setInterval(function() {
function randomNumber(min, max) {
return Math.random() * (max - min) + min;
}
hexBeat = randomNumber(1, 25);
if (hexBeat <= 20) {
console.log(hexBeat);
document.querySelector("#nachoCheddar01").style.backgroundColor = "green";
document.querySelector("#nachoCheddar01").style.left = `${document.querySelector("#nachoCheddar01").offsetLeft + 200}px`;
}
}, 1000)
}

Coin toss with JavaScript and HTML

I need help fixing my script. Basically, I want it to flip a coin and update a <span> with the result, i.e. if it's heads or tails. At the moment, nothing happens when I click the button.
JavaSript:
var heads = 0;
var tails = 0;
function click() {
x = (Math.floor(Math.random() * 2) == 0);
if(x){
flip("heads");
}else{
flip("tails");
}
};
function flip(coin) {
document.getElementById("result").innerHTML = coin;
};
HTML:
<button id="click" type="button">CLICK ME</button>
<p>
You got: <span id="result"></span>
</p>
That's simply because you need to attach the event handler:
document.getElementById('click').onclick = click;
var heads = 0;
var tails = 0;
function click() {
x = (Math.floor(Math.random() * 2) == 0);
if(x){
flip("heads");
}else{
flip("tails");
}
};
function flip(coin) {
document.getElementById("result").innerHTML = coin;
};
<button id="click" type="button">CLICK ME</button>
<p>
You got: <span id="result"></span>
</p>
var prob1 = Math.floor(Math.random() * 2) +1;
var prob2 = Math.floor(Math.random() * 2) +1;
if( prob1 === prob2){
document.write('You Got TAIL');
}else{
document.write('You Got HEAD');
document.getElementById('click').onclick = click;
var heads = 0;
var tails = 0;
function click() {
x = (Math.floor(Math.random() * 2) == 0);
if(x){
flip("heads");
}else{
flip("tails");
}
};
function flip(coin) {
document.getElementById("result").innerHTML = coin;
};
<button id="click" type="button" onclick="click()">CLICK ME</button>
<p>
You got: <span id="result"></span>
</p>
function flip(Throws) {
let coinArray = [];
for (var i = 0; i < Throws; i++) {
rndNo = Math.floor(Math.random() * 2 + 1);
if (rndNo === 1) {
Toss = 'H';
} else {
Toss = 'T'
} // if (rnd === 1)
coinArray.push(Toss);
}
return coinArray;
}
console.log(flip(10));
function flipHeadCoin() {
let coinArray = [];
let numHeads = 0;
do {
rndNo = Math.floor(Math.random() * 2 + 1);
// ternary operators
Toss = (rndNo === 1) ? 'H' : 'T';
numHeads += (Toss === 'H') ? 1: 0;
coinArray.push(Toss);
} while (numHeads < 6);
return coinArray;
}
console.log(flipHeadCoin());
const coinFlip = num_of_coin_flips => {
heads = 0;
tails = 0;
for(i = 0; i < num_of_coin_flips; i++){
randomNumber = Math.floor(Math.random() * 2);
roundNum = Math.round(randomNumber* 100) / 100;
roundNum === 0
? heads += 1
: tails += 1;
}
return `There are ${heads} heads and ${tails} tails. That's a ${((heads / num_of_coin_flips) * 100)} % / ${((tails / num_of_coin_flips) * 100)} % split`
}
console.log(coinFlip(3))
<!DOCTYPE html>
<html>
<body>
<p id="Another way"></p>
<script>
var x;
x = (Math.floor(Math.random() * 2) == 0);
if (x==1) {
x="Blue"
} else {
x="Red"
};
document.getElementById("Another way").innerHTML =
"The color of the pill is " + x + "!.";
</script>
</body>
</html>
And ofcourse this still needs an event handler ;) it's late guys :)

Alert box from function

The function is working great but Im missing why my alert box wont trigger after the click.
<html>
<script type="text/javascript">
function getRNG(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
function rollD20() {
document.getElementById("txtNumber").value = getRNG(1, 20);
}
if (txtNumber < 10) {
alert("Failure");
} else {
alert("Success");
}
</script>
<body>
<input type="text" disabled="disabled" size="2" id="txtNumber" />
<div id="output"></div>
<button onclick="rollD20();">Roll</button>
</body>
</html>
You have a closure issue. Should be:
<script type="text/javascript">
function getRNG(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
function rollD20() {
document.getElementById("txtNumber").value = getRNG(1, 20);
if (txtNumber < 10) {
alert("Failure");
}
else {
alert("Success");
}
}
</script>
The change was moving the closing bracket for the rollD20 function to be below your if/else statement.
Also worth noting, I don't see anywhere that you set txtNumber.
Perhaps what you meant was:
function rollD20() {
var txtNumber = getRNG(1, 20);
document.getElementById("txtNumber").value = txtNumber;
if (txtNumber < 10) {
alert("Failure");
}
else {
alert("Success");
}
}
If so, this could be further reduced (if so desired) to simply:
function rollD20() {
var txtNumber = document.getElementById("txtNumber").value = getRNG(1, 20);
alert(txtNumber < 10 ? "Failure" : "Success");
}
Because you didn't put it into the rollD20 function, so the if-else logic run only once, when the page loaded. To trigger it on every click, you must put it in the click event handler, like this:
<html>
<script type="text/javascript">
function getRNG(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
function rollD20() {
var txtNumber = document.getElementById("txtNumber").value = getRNG(1, 20);
if (txtNumber < 10) {
alert("Failure");
} else {
alert("Success");
}
}
</script>
<body>
<input type="text" disabled="disabled" size="2" id="txtNumber" />
<div id="output"></div>
<button onclick="rollD20();">Roll</button>
</body>
</html>
Also, I defined a variable named txtNumber.
well, the if...else logic is outside the function, but you probably want to store the result of getRND() in a variable too:
function rollD20() {
var result = getRNG(1, 20);
document.getElementById("txtNumber").value = result;
if (result < 10) {
alert("Failure");
}
else {
alert("Success");
}
}

Categories