Rotate Images JavaScript with PHP Directory Listing

This example demonstrates coordinating the JavaScript Image Rotator with a php array obtained from a directory listing of images. The rotation can be random or sequential and can be linked, responding with pause and resume onmouseover/mouseout.

The first image in this demonstration is selected at random from the array. You can display the first image in the direcory as the page is loaded if you prefer.

About the Code

The Rotate Images JavaScript, which this demo extends is quite easy to set up. The documentation contains general information for implementing the JavaScript portion, such as the script tags to be included and initialization.

Setup of the php portion of the code is very simple. There are two variables to set: $root and $path for locating the directory containing the images. For this demo, they are set as:

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

Two php functions are called: one to obtain the directory listing, an optional second one to select a random subset of those images for the rotation.

// 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 a JavaScript segment we place the following, which outputs the php values we need, the path to the images and the images array:

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 
}

More Information

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

See Licensing Information for use of the code. Please read dyn-web's Terms of Use if you plan to use our code.