Computing.Net > Forums > Web Development > javascript background random image

Computer Problems? Computing.Net has over 1,000,000 posts about all things technology related! Over 90% answered within 24 hours! Click here to get for your free account now!

javascript background random image

Reply to Message Icon

Name: BigShow
Date: April 23, 2008 at 10:07:39 Pacific
OS: xp
CPU/Ram: pentium
Manufacturer/Model: dell
Comment:

I need to make a script that will randomly choose a background image from 4 different images when the page loads and displays it, everytime it reloads it will be a different image.I think I need to use javascript and create a random number assign it to a variable then create an array of these 4 backgrounds, then create a function that chooses the array with that random number, then in the body have the onload function load it.

Here is what i have, it doesnt work.

any ideas


function get_random()
{
var ranNum= Math.floor(Math.random()*4);
return ranNum;
}

var whichImage = function get_random();

var back=new Array(4)
back[0]="bg1a.jpg";
back[1]="bg2a.jpg";
back[2]="bg3a.jpg";
back[3]="bg4a.jpg";



</script>

</head>
<body onload="javascript:back[whichImage]">


Report Offensive Message For Removal

Sponsored Link
Ads by Google

Response Number 1
Name: BigShow
Date: April 23, 2008 at 11:34:44 Pacific
Reply:

I figured it out, just in case anyone needs the script,

<SCRIPT LANGUAGE="JavaScript">

random_number= Math.floor(Math.random()* 4+1 );
// Loads the appropriate image and text color based on random number.
if (random_number==1) {
image="bg1a.jpg";
}
if (random_number==2) {
image="bg2a.jpg";
}
if (random_number==3) {
image="bg3a.jpg";
}
if (random_number==4) {
image="bg4a.jpg";
}

// End -->
</SCRIPT>
</head>

<body onload="document.body.background = image">
</body>
</html>



Report Offensive Follow Up For Removal

Response Number 2
Name: Beanonymous
Date: October 11, 2008 at 20:48:57 Pacific
Reply:

Hi sorry to be a pain and all but is it possible to incorporate this code into your current code? http://answers.yahoo.com/question/index?qid=20070616132155AAicr6Y


Report Offensive Follow Up For Removal
Reply to Message Icon

Related Posts

See More







Post Locked

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.


Go to Web Development Forum Home


Sponsored links

Ads by Google


Results for: javascript background random image

Javascript cross-frame image swap www.computing.net/answers/webdevel/javascript-crossframe-image-swap/2582.html

Javascript: Math.random prob. www.computing.net/answers/webdevel/javascript-mathrandom-prob/3365.html

images load partially or not at all www.computing.net/answers/webdevel/images-load-partially-or-not-at-all/2354.html