Edit to reflect the comment given by the OP. Pardon the jQuery.
Assuming the directory index you've got is a standard Apache Auto-Index page:
//jQuery doc.ready, because I'm too lazy to do something better ;)
$(function () {
var links = [];
$.ajax(
{
//url: location.pathname, // Use current page
url: '/directoryname/', //directory index of your choice
success: saveAjaxedLinks
}
);
function saveAjaxedLinks (data, e) {
// Scrape anchors off of page.
// Note -- there might be other anchors on the page
// that you don't want to pick up, say the "up a directory level" anchors.
// you can filter those out if you want, but you'll have to determine the criteria for doing so.
var directory = $('a', data);
//Get anchor nodes and store them.
links = directory.get();
//Assign event listener to button after the data is ready.
$('button#yourbuttonid').on( 'click', onclickGetRandomPage );
//uncomment to do action immediately.
//onclickGetRandomPage();
}
function onclickGetRandomPage (e) {
if ( !!e && !!e.preventDefault ) {
e.preventDefault();
}
//if no links on the index, do nothing.
if ( !links.length ) return;
//Get the a random index from the links.
var rnd = Math.floor( Math.random()*links.length);
for (var i = 0, len = links.length; i < len; i++ ) {
// Make sure there's an actual href inside the random link.
// Also, check to make sure the links arent just hashes. Not necessary if you're just using an apache auto-index.
// If there are certain types of links you don't want (eg. directory roots), you can filter them out here.
if ( !!links[rnd].href && links[rnd].href.replace( links[rnd].hash, '' ) !== (location.href.replace( location.hash, '' ) ) ) {
//console.log(links[rnd].href); //Log out the links if you're just testing
window.location.href = links[rnd].href;
break;
} else {
//That link was no good, get a different one.
rnd = Math.floor( Math.random()*links.length );
}
}
}
});