7

I've tried several tutorial on the web and none seems to work properly. What I'm trying to do is quite simple I think:

I have 9 different .jpg images that I need to randomly show up on page load - to be background. This should be fairly simple right?

Thanks,

EDIT (Sorry, forgot to attach the code - found in the web):

$(document).ready(function(){

    bgImageTotal=9;

    randomNumber = Math.round(Math.random()*(bgImageTotal-1))+1;

    imgPath=('../img/bg/'+randomNumber+'.jpg');

    $('body').css('background-image', ('url("'+imgPath+'")'));

});
James Montagne
  • 77,516
  • 14
  • 110
  • 130
asirgado
  • 225
  • 3
  • 4
  • 7
  • 2
    It is generally preferred if you post some code which you have tried to use which will not work rather than just ask people to write it for you. – James Montagne Jan 11 '12 at 22:34
  • True, sorry.. forgot to attach the code. – asirgado Jan 11 '12 at 22:36
  • Yeah, it'd all depend on what language you're using as to how you'd do it. – Paul Jan 11 '12 at 22:37
  • Related: [How to generate a random ID for body tag upon page load using a set array of IDs](http://stackoverflow.com/questions/8673090/how-to-generate-a-random-id-for-body-tag-upon-page-load-using-a-set-array-of-ids) – Rob W Jan 11 '12 at 22:38
  • 1
    The posted code assumes that your images are stored in a folder named `img` which is at the same level as the folder your html is in, inside of a subfolder named `bg`. It also assumes that your images are named `1.jpg`, `2.jpg` etc. Is this all true? – James Montagne Jan 11 '12 at 22:39

2 Answers2

23

Check out this tutorial: http://briancray.com/2009/12/28/simple-image-randomizer-jquery/

First create an array of images:

var images = ['image1.jpg', 'image2.jpg', 'image3.jpg', 'image4.jpg', 'image5.jpg'];

Then, set a random image as the background image:

$('body').css({'background-image': 'url(images/' + images[Math.floor(Math.random() *      images.length)] + ')'});

That should work no problem.

Jesse Pollak
  • 1,600
  • 1
  • 15
  • 20
0

using jQuery: $("body").css("background-image", "url(" + Math.floor(Math.random()*9) + ".jpg)");

This is assuming, that your images are named 0.jpg until 8.jpg and are in the same directory as your page.

ChrisiPK
  • 115
  • 3