To ensure your code runs properly, make sure it is executed after the DOM has loaded. You can achieve this by either moving the code below the </body>
tag or using the window.onload
handler.
It's important to remember that assignment statements should end with a ;
, not a ,
.
window.onload = function() {
var dir = 'http://seriousphotography.co.uk/HD-Site/images/album/01/';
var images = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10"];
var randomCount = Math.floor(Math.random() * images.length);
document.getElementById("image").style.backgroundImage = "url(" + dir + images[randomCount] + ".jpg" + ")";
};
For a more concise version:
window.onload = function() {
var dir = 'http://seriousphotography.co.uk/HD-Site/images/album/01/';
var images = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10"];
var randomCount = Math.floor(Math.random() * images.length);
document.getElementById("image").style.backgroundImage = "url(" + dir + images[randomCount] + ".jpg" + ")";
};
Check out Get random item from JavaScript array for reference.
Using classes and jQuery, you can simplify it further:
$("#image").addClass("image"+images[randomCount]);
Fiddle: http://jsfiddle.net/barmar/LgjzvcpL/12/