Published on: Friday 20th November 1998 By: Ben Allen
A picture gallery is used in preference to having many pictures on one page. The idea is to have one image in the HTML page, which can be changed to show other images by clicking on the buttons underneath. To do this with the minimal amount of code we should name the pictures in a sequence, e.g. if we had 20 pictures, we would name them image1.jpg through to image20.jpg.
If we had to display 20 different pictures in our gallery, we could write 20 different functions to display each one. Instead when the page loads, we can create an array of file names. The code for this is shown below.
Now we need to create a function for each button to call to "rotate" the images. The function will use a global variable to keep track of which image is currently being displayed. Each time the function is called it will load the next (or previous) image named in the ImageNames array into an image called myimage. The function will take an argument called direction, which tells it to go forward or backwards in the array. When the function is called direction will equal -1 or 1, depending on which image is to be loaded. It will also have two if control statements to make sure the global variable doesn't call image 21, which doesn't exist.
Only if the browser supports the images object will we actually alter the images source property.
Now we will create two buttons that look like this:
Each button calls the changeImage() function, but in a different direction:
<form> <input type="button" value="<<" onClick='changeImage(-1);'> <input type="button" value=">>" onClick='changeImage(1);'> </form>
The HTML for the image simply looks like:
<img src="image1.jpg" name="myimage">
If you prefer image buttons to the grey form buttons, then rather than using an image form tag, which won;t work in older versions of Netscape Navigator (as they didn;t originally support th onClick event handler, use image links:
The above code is fine if you want to have a fixed number of images. But what if you are constantly adding images to your collection? The code would need to be edited in a number of places. The script below needs only be altered once to allow for new images.
The constant NUMBER_OF_IMAGES is substituted into the script so that its value can be changed once to alter the entire script.
You can test the above using the following working example: