2

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];
}
1
  • remove the .src, as in, it should just be .style.backgroundImage = "url('http://image.com/example.png')" Commented Aug 12, 2012 at 17:11

1 Answer 1

3

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] + ")";
}
Sign up to request clarification or add additional context in comments.

3 Comments

Hey this works! Thank you So Much! So the backgroundImage is equal to "url(with some parameters)". I think one of the problems with the way I looked at it was I wanted to change the css property but javascript is really overriding the property. Thank you again.
Well, also you were looking at it as being more granular than it is. There is a style.background and a style.backgroundImage because there are CSS properties background and background-image. But you were trying to access style.backgroundImage.src which doesn't exist (there's no background-image.src property in CSS. :) ) Remember what you're setting is a CSS property, no more, no less. Which means you need to remember url() or px or whatever would go in the CSS if you were writing a .css file.
Excellent! I will try playing around with that some more. Hopefully it will become clearer with practice. Thanks again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.