Wednesday, 2 October 2013

JavaScript Slideshow

In this post, I will illustrate how to periodically change the image source of an 'img' element using JavaScript. This is a simple Slideshow, and doesn't show any animation in sliding in and sliding out of images. Images will be shown one after one at an interval of 3 seconds. Let's see the code now:

<!DOCTYPE html>
<title>JavaScript Slideshow</title>
<img >
var photos = ["file:///C:/Users/Public/Pictures/Sample Pictures/Tulips.jpg",
"file:///C:/Users/Public/Pictures/Sample Pictures/Penguins.jpg",
"file:///C:/Users/Public/Pictures/Sample Pictures/Lighthouse.jpg",
"file:///C:/Users/Public/Pictures/Sample Pictures/Koala.jpg",
"file:///C:/Users/Public/Pictures/Sample Pictures/Jellyfish.jpg"];
setInterval(changePhoto, 3000); //change image every 3 seconds
var imageElement = document.getElementsByTagName("img")[0];
imageElement.src = photos[0];
var arrayIndex = 0;
var arrayLength= photos.length;
function changePhoto() {
if (arrayIndex === arrayLength) {
arrayIndex = 0;
imageElement.src = photos[arrayIndex];

No comments:

Post a Comment