JavaScript Tutorial JavaScript Examples CSS Tutorial HTML Tutorial About Us

Lesson 29: Creating a Slideshow


In lesson 28, we have learned how to create rotating banners without links and with links. In this lesson, we will modify the JavaScript code for the rotating banners into a slideshow.The JavaScript code for the slideshow is almost similar to the JavaScript code of the rotating banners but it gives control to the user to choose the banner ads he or she wants to see by clicking on the forward and backward buttons.

To create the JavaScript slideshow, first of all, you need to create a few banner images using some graphics tools, or you can snap some photos with your digital camera or your smartphone. In our example, we have created four images and we named them as banner1.jpg, banner2.jpg, banner3.jpg, and banner4.jpg. Save the images in the same folder as the HTML file slideshow.htm which will be used to show the slides.

In the slideshow JavaScript code, we create an array MySlides to store the banner images using the following statement:

MySlides=new Array('banner1.jpg','banner2.jpg','banner3.jpg','banner4.jpg')

We use the variable Slide to indicate the index of the above array, where 0 represents the index of the first slide, 1 represents the index of the second slide and so on. We also created the function ShowSlides(SlideNumber) with the argument SlideNumber.

To call this function, we created two buttons within the body tag, the Forward button, and the Back button. Clicking the Forward will pass the value of 1 to the argument SlideNumber and clicking the Back button will pass the value of -1 to the argument SlideNumber. Using the statement:

Slide=Slide+SlideNumber

We can then load the next banner image or the previous banner image.

The statement

if (Slide>MySlides.length-1){Slide=0

is to go back to the first image and avoid the error of loading the next image after the final image has been reached. Similarly, the statement

if (Slide<0) {Slide=MySlides.length-1

is to fast forward to the last image and avoid the error of loading the image with the negative index

The following Statement is to display the current image by referencing the name of the <img> tag.

document.DisplaySlide.src=MySlides[Slide]

The Slideshow Script

<script>
MySlides=new Array('banner1.jpg','banner2.jpg','banner3.jpg','banner4.jpg')
Slide=0
function ShowSlides(SlideNumber){

{ Slide=Slide+SlideNumber
if (Slide>MySlides.length-1){
Slide=0
}
if (Slide<0) {
Slide=MySlides.length-1
}
document.DisplaySlide.src=MySlides[Slide]
}
}
</script>
The HTML
<div>
<P align="center"><img src="banner1.jpg" name="DisplaySlide" width="900" height="120" /><p>
<input type="button" value="Back" onclick="ShowSlides(-1)">
<input type="button" value="Forward" onclick="ShowSlides(1)">
</div>







Copyright©2008 Dr.Liew Voon Kiong. All rights reserved |Contact|Privacy Policy