• We should now be fully online following an overnight outage. Apologies for any inconvenience, we do not expect there to be any further issues.

Random Picture Selection on a website

Stiganator

Platinum Member
Oct 14, 2001
2,492
3
81
So I have a folder full of pictures. I want three of them to be randomly selected and displayed on the bottom of a webpage.

I have sample page similar to what I want, but the code is very chaotic and I don't understand it.

I am hesitant to use javascript because I feel like people dislike it for security reasons. Is this justified? I don't think they have a php server so I would like to stick with languages that don't need anything more than a basic web server.

What would you do?
 

CTho9305

Elite Member
Jul 26, 2000
9,214
1
81
You have two choices:
1. Client-side
A. JavaScript - easiest, most likely to work (no plugins required)
B. Java Applet - do NOT do this (takes forever to load)
C. Flash - overkill
2. Server-side
A. PHP - you said you don't have it
B. Perl - you might not have it either
C. Some other scripting language

A few people disable javascript for security reasons, but the very vast majority don't. Just make sure you have a reasonable fallback if the JS doesn't run.

<script>
var maxNum = 10; // assume you have pictures 0, 1, 2...9, 10.jpg in your folder
function doIt() {
var i;
for (i=0; i<3; i++) {
var img = document.getElementById("img"+i);
var num = parseInt(Math.random() * (maxNum+1)); // will almost always return 0, 1, ..., maxNum-1, maxNum, but very rarely maxNu+1
if (num > maxNum) num = maxNum; // handle the special case (if you don't do the +1, you'll almost never see the last image in the folder)
img.src = num+".jpg";
}
}
</script>
<body onload="doIt()">
<img src="1.jpg" id="img1"><img src="2.jpg" id="img2"><img src="3.jpg" id="img3">

Note that if JS is disabled, they'll just see 1.jpg, 2.jpg, and 3.jpg instead of garbage.
 

Stiganator

Platinum Member
Oct 14, 2001
2,492
3
81
Awesome, I was thinking of something like this. I think I might even one up it and get some experience with mysql now too.