Reputation: 21
I am a js newbie. I Have looked for answers to this particular issue but have not found an answer yet in this forum or others, so sorry if it's here and I missed it. I have a script that works for loading a random image from an array to an id element placed directly in the html when the page loads.
I'm trying to see if I can get it to do the same thing but do it for a background image in a id element in a css file. I have firebug and it doesn't give me any error messages with this but it doesn't work either.
window. onload = choosePic;
var myPix = new
Array("images/image1.gif", "images/image2.gif");
function choosePic() {
randomNum = Math.floor((Math.random() * myPix.length));
document.getElementById("headerAnimation").style.backgroundImage.src = myPix[randomNum];
}
Upvotes: 2
Views: 3473
Reputation: 8784
You have it almost right.
window.onload = choosePic;
var myPix = new Array("images/image1.gif", "images/image2.gif");
function choosePic() {
var randomNum = Math.floor((Math.random() * myPix.length));
document.getElementById("headerAnimation").style.backgroundImage =
"url(" + myPix[randomNum] + ")";
}
Upvotes: 3