Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
133
rated 0 times [  140] [ 7]  / answers: 1 / hits: 22243  / 13 Years ago, wed, january 11, 2012, 12:00:00

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+')'));

});

More From » jquery

 Answers
17

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.


[#88070] Tuesday, January 10, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
travion

Total Points: 137
Total Questions: 96
Total Answers: 103

Location: India
Member since Wed, Aug 4, 2021
3 Years ago
travion questions
Mon, Dec 16, 19, 00:00, 5 Years ago
Sat, Oct 19, 19, 00:00, 5 Years ago
Fri, Sep 20, 19, 00:00, 5 Years ago
Wed, Nov 14, 18, 00:00, 6 Years ago
Sun, Oct 28, 18, 00:00, 6 Years ago
;