Javascript Image Rotation

Just one of the things i’ve had to mess about with over the last few days, I had to add a bunch more pictures to our external webpage.  The front of the webpage (http://www.transend.com.au if you’re interested) and the secondary pages display little logo images in the top right of the screen.  Which images it displayed were randomly picked out of 7 or 8 different images for each section.  (Two images, each with 7 or 8 possibles).

I was asked to update that to display a random of 40 different pictures for each image, and while I was at it I optimised the javascript to make it easy to add more as time goes on (it was quite simple and a pain to maintain as it was, having been written by designers rather than coders đŸ˜‰ )

In anycase, heres the javascript snippet and how to use it.


    var imagenumber = 40;  // Enter the number of pictures you wish to display

    var randomNumber = Math.round( ( Math.random() * (imagenumber-1) ) );
    // Get a random number between >= 0 and
    images = new Array;
    for(var x=0; x     {
        images[x] = “randomimages/topimage” + (x+1) + “.jpg”;

        // This needs to change depending on how you position and name your image file.
        // The example assumes a folder “randomimages” that contains at least imagenumber of pictures
        // all labelled  topimage[imagenumber].jpg (So, in this example, topimage1.jpg to topimage40.jpg)
    }

    var image = images[randomNumber];

Thats the main script block to include in the section.  Later in the html code we need to include the following:

    document.write(““);

This will display the image with alternate text (for imageless browsers) and an id for easy css styling.  You can adapt this code anywhere you need random image display on a webpage. You could probably edit it to provide less random, guided progression of images over time as well, whatever takes your fancy.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s