...

View Full Version : Generating a random bg image



MePerson2k
07-26-2003, 02:11 AM
I just want you to know that, yes, I did search before posting. I tried the code I got and it doesn't work. Could someone please tell me what's wrong with it?

<html>
<head>
<script language="JavaScript">
<!--
image01= new Image(1024,768)
image01.src="http://www.mygpop.com/kh1.jpg"
image02= new Image(1024,768)
image02.src="http://www.mygpop.com/kh2.jpg"
image03= new Image(1024,768)
image03.src="http://www.mygpop.com/ff7cloud.jpg"
image04= new Image(1024,768)
image04.src="http://www.mygpop.com/naruto.jpg"
//-->
</script>
</head>

<script language="JavaScript">
function rand_int(num_1, num_2)
{
return((num_2)?Math.floor(Math.random()
*(num_2-num_1))+num_1:Math.floor
(Math.random()*num_1));
}
var bgs=["image01.src","image02.src","image03.src","image04.src"]'
var rand=rand_int(bgs.length);
document.write('<body background="'+bgs [rand]+'" bgcolor="#FFFFFF" link="#999999" vlink="#FFFFFF" bgproperties="fixed" text="#DDDDDD" onLoad="window.onresize=new Function('if (navigator.appVersion==\'Netscape\') history.go(0);');">');
</script>

</html>


thanks for any help you can give me

World-Craft
07-26-2003, 02:54 AM
You are calling it as a string, and the variable is an object (image)

Make the variable a string, containing the url. Then use the same code. (and no 'var' word). Oh, I cleaned up ur code a bit, it should work a bit more efficiently now ;)


<script>
var image=new Array();
image[0]="http://www.mygpop.com/kh1.jpg";
image[1]="http://www.mygpop.com/kh2.jpg";
image[2]="http://www.mygpop.com/ff7cloud.jpg";
image[3]="http://www.mygpop.com/naruto.jpg";

var rand=Math.random()*3
document.write("<style>body{");
switch (rand)
{
case 0:
document.write("background-image:url("+image[0]+")");
break
case 1:
document.write("background-image:url("+image[1]+")");
break
case 2:
document.write("background-image:url("+image[2]+")");
break
case 3:
document.write("background-image:url("+image[3]+")");
break
}
</script>

document.write("}</style>");

That should work.

Hope this helps

Cheers, Mat!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum