0

I'm building a site for myself. I Have made a header background that changes image every time you refresh. But sometimes there comes no image in the header.

Can anyone help?

Javascript:

addEventListener("load",init,false);

function init(event){

    var header = document.getElementById('mainheader');
    var pictures = new Array(3);
    pictures[0]="pictures/test1.jpg";
    pictures[1]="pictures/test2.gif";
    pictures[2]="pictures/test3.jpg";
    var numPics = pictures.length;
    if (document.images) {
        var chosenPic = Math.round((Math.random() * numPics));
        header.style.background = 'url(' + pictures[chosenPic] + ')';
    }
}

HTML:

<header id="mainheader">
<a href="index.html"><img src="pictures/untitled.png" alt="logo" id="imglogo"></a>

<nav id="cssmenu">
    <ul>
        <li class='active'><a href='index.html'><span>Home</span></a></li>
        <li><a href='about%20me.html'><span>About Me</span></a></li>
        <li><a href='contact.html'><span>Contact</span></a></li>
        <li class='last'><a href='pictures.html'><span>Pictures</span></a></li>
    </ul>
</nav>

Mritunjay
  • 25,338
  • 7
  • 55
  • 68
Brecht
  • 1
  • 1
  • For reference: http://stackoverflow.com/questions/3419928/how-can-i-return-a-random-value-from-an-array – Oleg Aug 30 '14 at 17:38

4 Answers4

0

Your problem is the randomizer code. Try:

var chosenPic = Math.floor(Math.random() * pictures.length);
Oleg
  • 9,341
  • 2
  • 43
  • 58
0

Your generated number is going to go from 0 to 3, 3 is outside the array bounds you need to use 1 less then the array length, or use floor instead of round

var chosenPic = Math.round((Math.random() * (numPics-1)));
Patrick Evans
  • 41,991
  • 6
  • 74
  • 87
0

Your JS can sometimes return 3 as your random number. Try this:

addEventListener("load",init,false);

function init(event){

var header = document.getElementById('mainheader');
var pictures = new Array(3);
pictures[0]="pictures/test1.jpg";
pictures[1]="pictures/test2.gif";
pictures[2]="pictures/test3.jpg";
var numPics = pictures.length;
if (document.images) {
    var chosenPic = Math.round((Math.random() * numPics));
    (chosenPic >= 3) ? 2 : chosenPic;
    header.style.background = 'url(' + pictures[chosenPic] + ')';
    alert(chosenPic);
}
}
Molg
  • 16
  • 2
0

The easiest solution:

   Math.floor(Math.random() * numPics);
theodore hogberg
  • 312
  • 3
  • 11