0

So I've tried several things to fix this but nothing seems to work. it was working OKAY earlier but something happened and now I cant get it to display a random image from a JS array in the target div.

  • renamed all the image files so they had no spaces
  • edited document.getElementById("profPic").innerHTML = '<img src="'+imagesArray[num]+'">'; several times to no avail
  • Checked SO for solutions/work around but concluded it must be something to do with the file formatting that i am unaware of.
  • Tried putting displayImage(); in the div container. Also tried with document.write

var imagesArray = ["img/mascotImages/CCF2_(281).jpg", "img/mascotImages/CCF2_(282).jpg"];

function displayImage() {

  var num = Math.floor(Math.random() * (imagesArray.length + 1));
  document.getElementById("profPic").innerHTML = '<img src="' + imagesArray[num] + '">';
}

function myFunction(e) {
  if ((e.target.id === 'mySearch' && e.keyCode === 13) || e.target.id === 'searchButton') {
    e.preventDefault();
    var searchValue = document.getElementById("mySearch").value;
    for (var i = 0; i < users.length; i++) {
      if (users[i]['last_name'] === searchValue) {
        document.getElementById("usernameOut").innerHTML = (users[i].username);
        document.getElementById("firstNameOut").innerHTML = (users[i].first_name);
        displayImage();
        return;
      }
    }
  }
}
<div id="return">
  <div id="profPic"></div>
  <!--profPic-->

  <div id="usernameOut"></div>
  <!--usernameOut-->

  <div id="firstNameOut"></div>
  <!--firstNameOut-->

</div>

What is supposed to happen is that when the user searches something in a search box, data from another array is displayed in <div id="usernameOut"> and <div id="firstNameOut"> etc. I wanted a random picture to display also when the user clicked search/hit enter.

Is something wrong with the naming conventions of the files? are they in one too many folders? i'm sure this is something very simple, but it's had me staring at it for several hours.

Rikin
  • 5,351
  • 2
  • 15
  • 22
gezer4000
  • 103
  • 1
  • 9
  • You might have problems with `imagesArray.length+1`, since the random value could end up outside of your range. See http://stackoverflow.com/q/4550505/215552, where it only uses `imagesArray.length`. Other than that, it's hard to say without the HTML that accompanies this code. – Heretic Monkey Feb 13 '17 at 23:34

1 Answers1

2

Arrays indexes start with 0, not 1. Therefore, with only 2 images in your array, the max index should be 1. But your code Math.floor(Math.random() * (imagesArray.length+1)) can at times return 2.

Just get rid of the +1:

Math.floor(Math.random() * imagesArray.length)

Community
  • 1
  • 1
Kevin Jantzer
  • 9,215
  • 2
  • 28
  • 52