<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="styles.css" />
<script src="styles.js"></script>
<title>Dice Roller</title>
</head>
<body>
<h1>Dice Roller</h1>
<p>Can't decide on what to eat? Or what to do? Our dice roller is perfect for this.</p>
<section>
<button class="roll-button" type="button" onclick="rollDice()">Roll</button>
<h1>
<script type="text/javascript">
var x = rollDice(1, 6);
output.innerHTML = x;
</script>
</h1>
</section>
</body>
</html>
function rollDice(a, b) {
dice = Math.floor(Math.random() * (b + 1)) + a
return dice
}
body {
background-color: orange;
font-family:system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
text-align: center;
font-size: 150%;
}
.roll-button {
height: 40px;
width: 80px;
font-family:'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
font-size: large;
}
I am trying to make a dice function that goes from JavaScript to HTML. How can I do this? I have tried multiple ideas and looked through guides, but they don’t help me at all. Thanks! (new to coding)
2
Answers
Here is an example using recommended practices.
I’ve modified the html such that numbers between 1 to 6 will be displayed as an h1 below the Roll button.
(There was also an issue with the rollDice function, it was displaying numbers from 1-7,so I’ve incorporated changes in that as well)
The document.getElementById("output") is used to get hold of the h1 that displays the output of the rolled dice.
Using document.getElementById("output").innerHTML = dice, the inner html of that element is set to the random dice number output.
The id of the h1 element below the Roll button is set to "output" so that it could be accessed using document.getElementById.
Here are the links I referred to answer this:
https://www.w3schools.com/jsref/met_document_getelementbyid.asp
https://www.w3schools.com/jsref/prop_html_innerhtml.asp