treehouse : what would you like to learn today?
Web Design Web Development iOS Development

[Solved] Random background image javascript help

  • I've been trying to get a div to load a different background image everytime the page is loaded, but can't get it to work at all. If anyone could help that would be greatly appreciated. Here is some code:

    CodePen

  • You have a couple of issues with your code. First of all, with codepen, you don't need to put the javascript inside of <script> tags. Secondly, to call a function, you need to use the function call operator, i.e. (). So, your window.onload = Randomize isn't actually assigning the function Randomize to window.onload.

    Here's my fixed codepen. I changed a couple of other things for style reasons, as well. Generally, when you're using fixed arrays, you don't use the myArray = new Array(element1, element2, ...) notation. Rather, define the array literally, using myArray = [ element1, element2, ... ]. Secondly, functions you create shouldn't be capitalized, unless they're a class.

  • It's probably a good idea to move those image paths to CSS and just put different classes on via the JavaScript.

    Here's an example: codepen

  • Thanks a lot guys. You've been very helpful.