Ask your JavaScript questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

display random images JavaScript


I want to display random images but "+ displayImg();" isn't accomplishing this

var imgArr = ["wq.png", "bq.png", "wk.png", "bk.png"];

function displayImg(){
var num = Math.floor(Math.random() * (imgArr.length));

document.getElementById("V" +i).value = good_1 + displayImg(); +good_2;


Answers (2)


Arnav Joy answers:

What your function is doing right now ?

User180435 comments:

The function is not invoked. probably better is

document.getElementById("V" +i).src = ; //etc.

User180435 comments:

for some reason, even a direct reference to an image fails.

document.getElementById("V" +i).src = "./images/pieces/wq.png";

User180435 comments:

But <img src = "images/pieces/wq.png" /> works perfectly.

User180435 comments:

I am using which is a text scroller.


Rainner Lins answers:

1. The random function needs to return the path to the image.

2. The thing you are trying to select using getElementById("V" +i) needs to be a image tag.

I don't know what your HTML code looks like, so I used the demo HTML code from and jQuery to select images inside the list and apply the random image function to them.

Here's the code on jsfiddle, but your images wont work there, although it should be working, if you use the developer console and inspect the image tags (right click > inspect), you should see that it has the random URL applied to it.