How to open a random image

Asked

Viewed 626 times

1

I have a new doubt and this has been the best place to find answers, since.
My problem and the next, I’m doing a school quiz for my son.
And a simple thing, at least it should be. A question with 3 answers, one right and two wrong. By clicking the right answer a commemorative image appears.
I wish this image was random so it wouldn’t get tiresome.
I’m using the following

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 in the 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 get it???
Thank you very much

1 answer

1


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

    You saved my day, thank you very much!!! I didn’t know how to call the result of a var into the attribute.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.