views:

1322

answers:

2

Hey,

I am trying to get jQuery to generate a random background on my site body absed off a number. So I'm trying to get it to generate either main1.jpg or main2.jpg and throw it into the body as a background.

For some reason it is only generating main2.jpg. Here is my code:

$(document).ready(function(){

    $("body").css({'background' : 'url(images/main1.jpg)'}).hide();
    $("body").css({'background' : 'url(images/main2.jpg)'}).hide();

    var randomNum = Math.floor(Math.random()*2); /* Pick random number */

    $("body").css({'background' : 'url(images/main:eq(' + randomNum + ').jpg)'}).show(); /* Select div with random number */

});

Thanks, Wade

+1  A: 

The reason it's doing that is the first call to setting the body background overwrites the first. It's the equivalent of doing:

var s = "hello";
s = "world";
alert(s); // world

What you want is something more like:

// this can contain as many images as you want
var images = ["images/main1.jpg", "images/main2.jpg"];

// preload. This is optional
var preload = new Array(images.length);
for (var i=0; i<images.length; i++) {
  preload[i] = $("<img>").("src", images[i]);
}

// assign one randomly
$(function() {
  var img = images[Math.floor(Math.random() * images.length)];
  $("body").css("background", "url(" + img + ")");
});

You could also adjust this to only preload the one image you use for the body background.

var img = images[Math.floor(Math.random() * images.length)];
var preload = $("<img>").attr("src", img);
$(function() {
  $("body").css("background", "url(" + img + ")");
});
cletus
+2  A: 

It is very confusing to see what you are trying to do. Right now you are hiding the body twice, then incorrectly adding a css rule, then showing the body. If you just want to set a random background, do this:

$(document).ready(function(){
    var randomNum = Math.ceil(Math.random()*2); /* Pick random number between 1 and 2 */
    $("body").css({'background' : 'url(images/main' + randomNum + '.jpg)'});
});

If you are wanting to add two divs and show one randomly, do this:

$(document).ready(function(){
    /* Pick random number between 1 and 2 */
    var randomNum = Math.ceil(Math.random()*2); 
    $.each([1,2], function(){
       var $div = $('<div class="background" style="background-image: url(images/main' + this + '.jpg)"></div>');
       if( this !== randomNum ) $div.hide();
       $div.appendTo( document.body );
    });
})
Doug Neiner
Thanks. You can tell I know jQuery well.
Wade D Ouellet
@Wade, no worries! Sorry if I sounding insulting at all, SO is the place to bring your questions! Do you have any questions about what I did different than your solution?
Doug Neiner