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, with pause and resume on mouseover and mouseout.

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

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

About the Code

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, they are set as:

$path = '/images/rotator/';

Two php functions are called: one to obtain the directory listing, a second 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 

Back to top