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

display random images JavaScript

  • REFUNDED

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

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

function displayImg(){
var num = Math.floor(Math.random() * (imgArr.length));
document.canvas.src="image/pieces/"+imgArr[num];
}

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


</script>

Answers (2)

2019-07-28

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 https://github.com/nishadmenezes/super-treadmill.js which is a text scroller.

2019-07-28

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 https://github.com/nishadmenezes/super-treadmill.js 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.

https://jsfiddle.net/rainnerlins/4rg3n1ch/