Rotate Images JavaScript with PHP Directory Listing

The JavaScript Image Rotator is demonstrated on this page rotating an array of images obtained from a php directory listing. The image rotation can be random or sequential. Images can be linked with pause and resume on mouseover and mouseout. Here we demonstrate with random rotation of linked images.

The download file contains examples demonstrating both sequential and random rotation.

Instructions

The Rotate Images documentation contains general information for implementing the JavaScript portion of the code, such as the script tags to be included and initialization. To set up the php portion of the code, specify values for two variables, $root and $path, for locating the directory containing the images. For this demo, since we are specifying the path to the images from the server root, they are set as follows:

$root = $_SERVER['DOCUMENT_ROOT'];
$path = '/images/rotator/';

If your images are in a directory under the document displaying them, $root would be an empty string:

$root = '';
$path = 'images/';

Only two functions are required for the script. The first function, getImagesFromDir, obtains a list of images from the directory you specify. The second function, getRandomSubset, allows you to specify how many images you would like to be included in the rotation. Pass this number as the second argument to the function and an array of that length will be returned.

// Obtain list of images from directory 
$imgList = getImagesFromDir($root . $path);

// Get a randomly selected subset from array
// optional second argument specifies how many 
$newList = getRandomSubset($imgList, 10);

The only remaining task is to translate the php array into a string for use by JavaScript:

// prep images list for JavaScript
$imgs = '["' . implode('", "', $newList) . '"]';

In the rotator properties, we use php to output the path and the images array:

<script type="text/javascript">
var rotator = {
    path: '<?php echo $path ?>',
    id:   'rotate_img',
    bRand: true,
    bMouse: true,
    images: <?php echo $imgs ?>,
    actions: ['.'] // Image linked, all point to same URL 
}
</script>

Download Examples

The download file contains examples demonstrating both sequential and random rotation.

Back to top