I\'ve been following some tutorials on how to randomize an image by setting up an array in Javascript. It\'s not working - the image itself is not appearing, not even any e
Oh man, this is embarrassing. Crazy how much you can learn in 3 years. I think the most optimal way of doing this would be the following (assuming there is no folder structure pattern). Haven't tested but should work.
var images = ["img/who/1.jpg","img/who/2.jpg","img/who/3.jpg"];
function getRandomImage(){
var rnd = Math.floor(Math.random() * images.length);
return images[rnd];
}
function changeImage(){
var img = document.querySelector("#myImg");
img.src = getRandomImage();
}
function init(){
var el = document.querySelector(".myClass");
el.onclick = changeImage;
}
window.onload = init;
What was I thinking assigning an array to [1] and then doing an if check? I'll never know.