View Full Version : JS or AJAX for loading ramdom image from directory listing

01-01-2008, 09:40 PM
I am looking for a JS or AJAX that can load a random image in a browser from a directory of images. I have found dozens of scripts that require declaring every image as a variable or in an array. I want my script to take an image directory path as a variable and load an image from a list of image names in an image directory.

Does anyone know of a JS script that will do this?


rnd me
01-02-2008, 03:54 AM
it kinda depends on the server where the images will be hosted.

if it supports webDAV, i have some ready to go code for you.

if you are able to view the directory listing when you point the browser to the image directory without a filename (eg "mysite.com/images/"), then you can ajax that directory location, and comb the resposnseText with a regexp something like (/[\w\d\_\.]+jpg/gmi), or parse the document into a DOM tree and return the href of all "a" tags that contain '.jpg'.

01-02-2008, 05:40 AM
Yes, the server supports directory browsing. do you have a finished script you could post?


rnd me
01-02-2008, 06:34 AM
function obVals(ob) {
var r = [];
var i = 0;
for (var z in ob) {
if (ob && ob.hasOwnProperty && ob.hasOwnProperty(z)) {
r[i++] = ob[z];
return r;

function newajax() {
var ox = null;
if (window.XMLHttpRequest) {
ox = new XMLHttpRequest;
} else if (window.ActiveXObject) {
ox = new ActiveXObject("Microsoft.XMLHTTP");
return ox;

function sGet(turl){
var XHRt = newajax();
XHRt.open("GET", turl, false);
XHRt.setRequestHeader("Content-Type", "text/html");
XHRt.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
return XHRt.responseText;
}//end sGet

function dir(paf) {
var b = sGet(paf).bold().bold();
var bo=document.createElement("b");
var c = obVals(bo.getElementsByTagName("a"));
var out=[];
for(var z =0; z< c.length;z++){
if(c[z].href && c[z].href.match(/jpg/ig)){ out[out.length]=c[z].href} //end if jpg
return out;
}//end function dir


this assumes a subdirectory named images in the page's folder...

rnd me
01-02-2008, 06:38 AM
for a random image from the results array coming from "dir":

function Rnd(w) {
return parseInt(Math.random() * (w + 1));

Array.prototype.random = function () {
return this[Rnd(this.length - 1)];