- If you are using Apache as your
web server, and
- if you can configure
it to provide a default directory
listing for your images folder (use
the appropriate options in
httpd.conf
and/or .htaccess
), and
- if you don't care that the list of
images is available to everyone who
visits your web site,
then you don't need PHP or any other server-side processing.
You can use XMLHttpRequest (or the jQuery ajax function, which is a nice wrapper) to get the listing for the folder. The response will be HTML and it will look something like this:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
<title>Index of /demo1/images</title>
</head>
<body>
<h1>Index of /demo1/images</h1>
<pre><img src="/icons/blank.gif" alt="Icon "> <a href="?C=N;O=D">Name</a> <a href="?C=M;O=A">Last modified</a> <a href="?C=S;O=A">Size</a> <a href="?C=D;O=A">Description</a><hr><img src="/icons/back.gif" alt="[DIR]"> <a href="/demo1">Parent Directory</a> -
<img src="/icons/image2.gif" alt="[IMG]"> <a href="tree.gif">tree.gif</a> 17-Mar-2009 12:58 6.2K
<img src="/icons/image2.gif" alt="[IMG]"> <a href="house.gif">house.gif</a> 17-Mar-2009 12:58 6.5K
<img src="/icons/image2.gif" alt="[IMG]"> <a href="car.gif">car.gif</a> 02-Mar-2009 15:37 8.4K
<img src="/icons/image2.gif" alt="[IMG]"> <a href="elephant.jpg">elephant.jpg</a> 02-Mar-2009 15:37 3.4K
<hr></pre>
<address>Apache/2.0.63 (Unix) Server at zeppo Port 80</address>
</body></html>
Since this output is pretty predictable, you might try parsing out the filenames using a JavaScript regular expression, but it's probably just as easy and more robust to create a hidden DIV on your page, put the HTML response into that DIV, and then use DOM methods to find <a href>
s that are after <img>
tags with an alt="[IMG]"
attribute. Once again, using jQuery Selectors or similar helper methods available in other toolkits will make this DOM parsing pretty easy.
Once you have the URL of the new image (parsed from the href
), you can set the new CSS background for your div with the .style.backgroundImage
property.