Buchwald said the following on 2/19/2006 12:53 PM:[color=blue]
> hello group,
>
> I have a long (large) script that shows a random picture when a
> webpage is refreshed. It's long because i have a lot of pictures: 246[/color]
Its long because you wrote it wrong. It is also bad code.
[color=blue]
> Here is some code:
> -----------------------------------------------------------------------------------------------
>
> <!--[/color]
If all the pictures are named as you have them, the image# variable is
not needed.
image###="smallpics/###-smallpic.jpg"
Is the format for the image name. You can generate that without having
to define it 246 times.
Then you create an Array to hold the alt text:
var altText = new Array();
altText['001'] = "Alt text for image 001";
altText['002'] = "Alt text for image 002";
....
altText['245'] = "Alt text for image 245";
altText['246'] = "Alt text for image 246";
[color=blue]
>
> len=246[/color]
len now equals altText.length, no need to hard-code it.
[color=blue]
>
> now=new Date()
> now=now.getSeconds()
> rnd=now%len[/color]
function Random(x) { return Math.floor(x*Math.random()) }
rnd = Random(altText.length);
[color=blue]
> image=eval("image"+rnd)[/color]
eval, and it's use, especially in this case, is indicative of bad code.
It's not needed.
imageRef = window['image' + rnd];
But, it is not needed.
[color=blue]
> alt=eval("alt"+rnd)[/color]
ditto.
[color=blue]
> document.write("<img src='" + image + "' alt='" + alt + "'
> border=0></a>")[/color]
document.write('<img src="img'+rnd+'smallpics/'+rnd+'-smallpic.jpg"
border="0" alt="'+altText[rnd]+'">');
all on one line.
[color=blue]
>
> -----------------------------------------------------------------------------------------------
>
> Can someone make it shorter for me?[/color]
var altText = new Array();
altText['001'] = "Alt text for image 001";
altText['002'] = "Alt text for image 002";
.......
altText['245'] = "Alt text for image 245";
altText['246'] = "Alt text for image 246";
function Random(x) { return Math.floor(x*Math.random()) }
rnd = Random(altText.length);
document.write('<img src="img'+rnd+'smallpics/'+rnd+'-smallpic.jpg"
border="0" alt="'+altText[rnd]+'">');
But, all of that would be better done on the server.
Now, all you have to do is add an altText'###' definition.
--
Randy
comp.lang.javascript FAQ -
http://jibbering.com/faq & newsgroup weekly
Javascript Best Practices -
http://www.JavascriptToolbox.com/bestpractices/