0

I'm trying to create an array from a for loop. Once the array is created I need to pick a random value in the array to display. In this case the values are pictures 1-4.png. I'm running into some trouble because the array looks like it's not being created, console says "Cannot set property 'src' of null".

var imgstart = 1;
var imgend = 4;

var arrimg = [];

for (var i = imgstart; i < imgend+1; i++) {
  arrimg.push(i)
}

window.onload = choosePic;

function choosePic() {
  var randomNum = Math.floor(Math.random() * arrimg.length);
  document.getElementById("myPicture").src = arrimg[randomNum] + '.png';
}
<img id="myPicture" />
MoLow
  • 3,056
  • 2
  • 21
  • 41
infosec
  • 39
  • 6
  • 6
    The error tells you that there isn't an element with an ID 'myPicture' – baao Dec 13 '15 at 22:18
  • Possible duplicate of [Cannot set property 'src' of null](http://stackoverflow.com/questions/17237142/cannot-set-property-src-of-null) – radubogdan Dec 13 '15 at 22:21
  • Can you post your HTML as well so we can see where `myPicture` is being referenced from? – Lucien Stals Dec 13 '15 at 22:25
  • Assure you have (if not create) an img-tag with id 'myPicture' in your html. – lboshuizen Dec 13 '15 at 22:29
  • Thanks very much, I put in html and it works. Now my only problem is that it says ERR_FILE_NOT_FOUND because the random number in array does not have .png. How can I add this to my code? – infosec Dec 13 '15 at 23:48
  • just add `'.png'` to the random selection like `document.getElementById("myPicture").src = arrimg[randomNum] + '.png';` – Nina Scholz Dec 14 '15 at 11:22

0 Answers0