3

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">');
Mikev
  • 2,012
  • 1
  • 15
  • 27
KX0
  • 99
  • 1
  • 3
  • 10

3 Answers3

2

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');
Varghese Mathai
  • 411
  • 3
  • 11
1

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>
0

You should set the innerHTML of a parent element rather than writing the element onto the page:

<div id="roll-dice">
    <button type="button" value="Trow dice" onclick="rolldice()">Roll dice</button>
    <span id="roll-result"></span>
</div>

JS:

var rollResult = Math.floor(Math.random() * 6) + 1;
var imageContainer = document.getElementById("roll-result");
if (rollResult == 1) imageContainer.innerHTML = '<img src="1.jpg">';
else if (rollResult == 2) imageContainer.innerHTML = '<img src="2.jpg">';
else if (rollResult == 3) imageContainer.innerHTML = '<img src="3.jpg">';
else if (rollResult == 4) imageContainer.innerHTML = '<img src="4.jpg">';
else if (rollResult == 5) imageContainer.innerHTML = '<img src="5.jpg">';
else  imageContainer.innerHTML = '<img src="6.jpg">';

And you can even bypass all the if statements and just use this code, which does exactly the same thing as the above except it is one line long:

document.getElementById("roll-result").innerHTML = '<img src="' + (Math.floor(Math.random() * 6) + 1) + '" />

Hopefully this helps!

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79