Slideshows are quite common on sites that have lots of images that need to be displayed for your visitors. Using just plain JavaScript, you can build a very simple slideshow using just a few lines of code. In this tutorial, we will go over a simple slideshow example built with JavaScript.
Feel free to use the example code shown below and build upon it so you can add more sophisticated components for your slideshow. Using the example below, you can control how many images are included in the show and the duration of each slide.
The HTML
The only HTML code needed is a simple <div>
containing one <img />
(image) element. Make sure that you assign an id
to the image element. Here is an example…
<div>
<img id="image1" />
</div>
The CSS
There isn’t any CSS code that is required for this slideshow to function. However, if you would like to add additional styles to the <div>
element and/or image element, you could do so.
The JavaScript
As you can see in the example below, there is not much JavaScript code needed for this example. The first few lines are used to set up our variables. imgArray
is an array used to keep all of the image source information.
The curIndex
variable is used to keep track of the current image being displayed in our show. imgDuration
is used to set the amount of time (in milliseconds) the image will be displayed before displaying the next image.
The function called slideShow()
is where the magic happens. There are only a few lines of code. The first line is used to assign the image element a new image source. As the curIndex
variable changes, the image element will display a different image.
After the image source is assigned, the curIndex
variable is incremented by one. Once the curIndex
variable equals the total number of images in our array, the variable is assigned a value of 0 so that the first image is displayed once again. The last line in the function creates a sort of loop for our function. Here is the JavaScript code…
<script>
var imgArray = [
'images/image1.jpg',
'images/image2.jpg',
'images/image3.jpg'
];
var curIndex = 0;
var imgDuration = 5000;
function slideShow() {
document.getElementById('image1').src = imgArray[curIndex];
curIndex++;
if (curIndex == imgArray.length) { curIndex = 0; }
setTimeout("slideShow()", imgDuration);
}
slideShow();
</script>
Complete Example
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Slideshow Demo</title>
</head>
<body>
<div>
<img id="image1" />
</div>
<script>
var imgArray = [
'images/image1.jpg',
'images/image2.jpg',
'images/image3.jpg'
];
var curIndex = 0;
var imgDuration = 5000;
function slideShow() {
document.getElementById('image1').src = imgArray[curIndex];
curIndex++;
if (curIndex == imgArray.length) { curIndex = 0; }
setTimeout("slideShow()", imgDuration);
}
slideShow();
</script>
</body>
</html>