I am trying to print out images on the dice, instead of just the number. But when i am using document.write, it just opens a new tab, and shows the picture. What should i use to print it out, with the button i have?
<div id="roll-dice">
<button type="button" value="Trow dice" onclick="rolldice()">Roll dice</button>
<span id="roll-result"></span>
</div>
var rollResult = Math.floor(Math.random() * 6) + 1;
if (rollResult == 1) document.write('<img src="1.jpg">');
else if (rollResult == 2) document.write('<img src="2.jpg">');
else if (rollResult == 3) document.write('<img src="3.jpg">');
else if (rollResult == 4) document.write('<img src="4.jpg">');
else if (rollResult == 5) document.write('<img src="5.jpg">');
else document.write('<img src="6.jpg">');
Use a picturebox and modify its source
<img src="" id="pic-result"/>
javascript code :
var rollResult = Math.floor(Math.random() * 6) + 1;
var pic = document.getElementById("pic-result");
if (rollResult == 1) pic.setAttribute('src', '1.jpg');
else if (rollResult == 2) pic.setAttribute('src', '2.jpg');
else if (rollResult == 3) pic.setAttribute('src', '3.jpg');
else if (rollResult == 4) pic.setAttribute('src', '4.jpg');
else if (rollResult == 5) pic.setAttribute('src', '5.jpg>');
else pic.setAttribute('src', '6.jpg');
You should be able to achieve this with innerHTML on #roll-result:
var diceResult = document.querySelector('#roll-result');
function rolldice() {
var rollResult = Math.floor(Math.random() * 6) + 1;
diceResult.innerHTML = '<img src="' + rollResult + '.jpg">';
}
<div id="roll-dice">
<button type="button" value="Trow dice" onclick="rolldice()">Roll dice</button>
<span id="roll-result"></span>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With