How to open a random image
I have a new doubt and this has been the best place to find answers, since Ja agradeco.
My problem and the following, I am doing a school questionnaire for my child.
And one simple thing, at least it should be. A question with 3 answers, one right and two wrong. By clicking on the right answer a commemorative image appears.
I would like this image to be random so as not to become tiresome.
I'm using the next
function SIM() {
var oImg = document.createElement("img");
oImg.setAttribute('src', 'img/certo.jpg');
oImg.setAttribute('alt', 'na');
oImg.setAttribute('height', '200px');
oImg.setAttribute('width', '200px');
document.body.appendChild(oImg);
}
And no body
<button id="SIM" onclick="SIM();">6</button>
I would like to have 10 images of celebration and I was thinking of something like
function SIM() {
var oImg = document.createElement("img");
oImg.setAttribute('src', '**NUMERO DE 1~10 ALEATORIO**.jpg');
oImg.setAttribute('alt', 'na');
oImg.setAttribute('height', '200px');
oImg.setAttribute('width', '200px');
document.body.appendChild(oImg);
}
Is there any way to achieve this???
Thank you very much
1
1 answers
To create a random number you can do Math.round(Math.random() * 10)
.
function SIM() {
var oImg = document.createElement("img");
var nr = Math.round(Math.random() * 10);
oImg.setAttribute('src', nr + '.jpg');
oImg.setAttribute('alt', 'na');
oImg.setAttribute('height', '200px');
oImg.setAttribute('width', '200px');
document.body.appendChild(oImg);
}
1
Author: Sergio, 2017-07-02 14:06:52