how to change image dynamically by js with random number code example

Example 1: how to change image dynamically by js with random number

let imageArray =new Array();

imageArray.push("images/dice1.png");
imageArray.push("images/dice2.png");
imageArray.push("images/dice3.png");
imageArray.push("images/dice4.png");
imageArray.push("images/dice5.png");
imageArray.push("images/dice6.png");


function randomGen(){
    let randomVar=Math.ceil(Math.random()*6) ;
    return randomVar;
}

document.querySelector("#dice1").lastElementChild.setAttribute("src",imageArray[randomGen()]);

Example 2: how to change image dynamically by js with random number

let imageArray =new Array();

imageArray.push("images/dice1.png");
imageArray.push("images/dice2.png");
imageArray.push("images/dice3.png");
imageArray.push("images/dice4.png");
imageArray.push("images/dice5.png");
imageArray.push("images/dice6.png");


function randomGen(){
    let randomVar=Math.ceil(Math.random()*6) ;
    return randomVar;
}

document.querySelector("#dice1").lastElementChild.setAttribute("src",imageArray[randomGen()]);

Tags:

Misc Example