I'm still new in JavaScript. I am trying to make a program that contains 2 buttons and once a button is clicked, it creates a random number.
The problem is that when I'm trying to compare them, it is not showing which one is bigger. First I thought the problem is that the variables aren't global but it didn't change anything.
Can someone help me find the problem please?
Here is the JavaScript code:
var par1 = document.getElementById("para1");
var par2 = document.getElementById("para2");
var winner = document.getElementById("win");
function button1() {
num1 = Math.floor(Math.random() * 7);
par1.innerHTML = num1;
}
function button2() {
num2 = Math.floor(Math.random() * 7);
par2.innerHTML = num2;
}
if (num1 > num2) {
winner.innerHTML = "the winner is player 1";
} else {
winner.innerHTML = "the winner is player 2";
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>dicestimulator</title>
<link rel="stylesheet" href="dicestimulator.css">
</head>
<body>
<div class="container">
<div>
<h1>Player1</h1>
<button type="button" name="button1" onclick="button1()" id="but1">roll
dice</button>
<p id="para1">Click the button to see what you get</p>
</div>
<div>
<h1>Player2</h1>
<button type="button" name="button2" id="but2" onclick="button2()">roll
dice</button>
<p id="para2">Click the button to see what you get</p>
</div>
<p id="win">let's see who wins!!!</p>
<script src="dicestimulator.js"></script>
</div>
</body>
</html>
if(num1>num2){
winner.innerHTML="the winner is player 1";
}else{
winner.innerHTML="the winner is player 2";
}
You are not calling the above block no where in your HTML code.
My solution for you make a third button that calls the function getwinner
function getWinner() {
if(par1.val>par2.val){
winner.innerHTML="the winner is player 1";
} else{
winner.innerHTML="the winner is player 2";
}
}
Please note that you cannot call local variables created in functions outside those functions. num1 and num2 cease to exist after the scope of the function that created them.