Home > Back-end >  JavaScript - How can I change image src based on a random number?
JavaScript - How can I change image src based on a random number?

Time:07-31

I have a random number generator that gives me a value between 1 and 6 (N).

I want to change the image SRC based on what number I get.

for instance, I have 6 images named [image1, image2, image3, image4, image5, image6].

let N = Math.random() * 6;
N = Math.floor(N);
document.querySelector(".img").src = `images/image${N}.png `;

I think the problem is caused by JS parsing images/img${N}.png as a HTML code due to ${N} being JavaScript code and HTML not being able to assign a value to it.

is there another way of writing this without using if / else if for every value of N?

like so =>

let N = Math.random() * 6;
N = Math.floor(N);
if (N === 1) {
    document.querySelector(".img1").src = "images/image1.png";
} else if (N === 2) {
    document.querySelector(".img1").src = "images/image2.png";
} else if (N === 3) {
    document.querySelector(".img1").src = "images/image3.png";
} else if (N === 4) {
    document.querySelector(".img1").src = "images/image4.png";
} else if (N === 5) {
    document.querySelector(".img1").src = "images/image5.png";
} else {
    document.querySelector(".img1").src = "images/image6.png";
}

CodePudding user response:

Your problem is a superfluous space at the end of the template/string

document.querySelector(".img").src = `images/image${N}.png `;
//                                                        ^

and missing one for one based counting.

Your actual random values are 0 ... 5, but you need 1 ... 6.

You could take a shorter approach by moving the random/flooring part into the expression.

document.querySelector(".img").src = `images/image${Math.floor(Math.random() * 6)   1}.png`;

const n = Math.floor(Math.random() * 6)   1;

console.log(`images/image${n}.png`);

CodePudding user response:

You can use array index like this:

let N = Math.random() * 6;
N = Math.floor(N);
const imgs = [image1, image2, image3, image4, image5, image6]
document.querySelector(".img1").src = imgs[N];

CodePudding user response:

You can use something like this :

let N = 6 // no of images
const imageBase='images/image';// relative or absolute url
document.querySelector(".img").src = `${imageBase}${Math.floor(Math.random() * N)}.png`;
  • Related