Create A Simple User Controlled Plain JavaScript Slideshow

Introduction

 
Today, I would like to share with you a simple method of creating a JavaScript slideshow. The slideshow I am going to show you is as simple as it gets. It will display some images and the user will be able to click on the buttons to cycle through the images.
 
There are many situations where a slideshow such as this is required and it is a very common Web development requirement. There are many different tutorials and guides out there, instructing you on how to build a slide show, but most of them are vastly more complex than what we are going to build today.
 
In a previous article, we discussed adding/attaching events in a way that works cross-browser. We will be using it today. If you haven’t had a chance to check it out, please go to:
In this article, I discussed a lightweight Cross-Browser solution for adding JavaScript events. Head over to the post and have a quick read and grab the code. If, due to any reason, you are unable to visit that post, here is the code,
  1. window.addingEvent = function (event, target, method) {    
  2.    if (target.addEventListener) {    
  3.       target.addEventListener(event, method, false);    
  4.    }   
  5.    else if (target.attachEvent) {    
  6.       target.attachEvent("on" + event, method);    
  7.    }    
  8. }   
Take that code and put it in a JavaScript file to include in our project, mine is called genericEventHandler.js.
 
Note
 
I highly recommend reading the post, as it explains the code and also how to use it.
 
Now we need to create a couple of files, one of which is an HTML page (index.html) and the other is a JavaScript file (imgGal.js)
 
Open your HTML page and in the head tags add:
  1. <script src="GenericEventHandler.js" type="text/javascript"></script>    
  2. <script src="imgGal.js" type="text/javascript"></script> 
These script tags will link to our JavaScript files.
 
Next, we will add some mark-up in between the body tags:
  1. <div id="slideShow">    
  2.     <img id="slideimage" name="image_0" src="cent.jpg" height="400" width="400" alt="Plain vanilla js slide show" />    
  3.     <form name="slideform">    
  4.         <input type="button" id="prevbtn" value="Previous" />    
  5.         <input type="button" id="nextbtn" value="Next" />    
  6.     </form>    
  7.     
  8. </div>   
This HTML mark-up displays an image and sets its ID and name to the specific values that JavaScript will use. It also creates a form, which contains the back and forward buttons.
 
Now, we have written our HTML. Therefore, we can get into the interesting stuff with the help of JavaScript.
 
Open up imgGal.js and add the following array, shown below:
  1. var pics = ['images/cent.jpg''images/chick.png''images/spaceStation.jpg''images/rockandironman.png'];   
Note
 
The ‘images/’ part of each item in the array is the folder in which the images are stored and then comes the file name.
 
Next, we will create the function that moves us forward through the slideshow.
  1. function nxtImg() {    
  2.    var img = document.getElementById("slideimage");    
  3.    var imgName = img.name.split("_");    
  4.    var index = imgName[1];    
  5.    if (index == pics.length-1) {    
  6.       index = 0;    
  7.    }   
  8.    else {    
  9.       index++;    
  10.    }    
  11.    img.src = pics[index];    
  12.    img.name = "image_" + index;    
  13. }   
This function will be added to the click event of the next button. I will show you in a moment. When the function is called, it retrieves the image object from the HTML img tag, by using document.getElementById().
 
Next, it splits the name attribute of that image at the underscore character, so the function can obtain the number from the ending characters of the name attribute. It stores that number in the index variable.
 
The next part of the code performs a conditional test, that checks whether the value of the index variable is equal to the length of the pics array minus 1 or not. If this condition is true, which means the user has reached the end of the slideshow, then the script sets the value of the index variable to 0, taking the user back to the first slide. If this condition is not true then the code increments the value of the index by 1.
 
The last two lines of our function set the src attribute to the new image and it also sets the name attribute appropriately so that next time, the code goes through the function and the current index can be determined.
 
Now, we have discussed the function. In order to implement it, one needs to go into the HTML page and somewhere near the closing body tag add a set of script tags, shown below:
  1. <script type="text/javascript">    
  2.     
  3. </script>   
In between the opening and closing script tags, we need to add our function to click the event of the next button. To do that, we need to call our little helper, window.addingEvent. We need to tell our function what event do we want to add, the element which we want to add the event to and then we tell it what to do when the event has been raised, shown below:
  1. var nxt = document.getElementById("nextbtn");    
  2. window.addingEvent('click', nxt, function () {    
  3.    nxtImg();    
  4. });   
If you run your page in a browser, you’ll see that you can go forward through the slideshow all the way until the last slide, at which point it takes you back to the beginning again.
 
As you can see, the previous button currently does nothing, but that is all about to change. We will create a function, that is similar to the nextImage() function. We will add this function to the click event of the previous button.
 
Open up imgGal.js and have a go at creating your prvImg() function. The code will be similar to the nxtImg() function except the conditional. If the index = 0, the slideshow is at the first image. Therefore, the function needs to loop back to the last image else the code moves backward by one index, showing the previous image.
 
Here is the code to move backward through the slideshow:
  1. function prvImg() {    
  2.    var img = document.getElementById("slideimage");    
  3.    var imgName = img.name.split("_");    
  4.    var index = imgName[1];    
  5.    if (index == 0) {    
  6.        index = pics.length - 1;    
  7.    }   
  8.    else {    
  9.         index--;    
  10.    }    
  11.    img.src = pics[index];    
  12.    img.name = "image_" + index;    
  13. }   
We also need to raise the event, when the button has been clicked. Therefore, go to your HTML page and find the Script block that we used to add the event to the next button. We need to do the same as we did with the next button except with the corresponding button and function, as shown below:  
  1. var prv = document.getElementById("prevbtn");    
  2. window.addingEvent('click', prv, function () {    
  3.    prvImg();    
  4. });   
Now, run your page in a Browser and you’ll see that you can cycle through the slideshow in whichever direction you wish to.
 

Summary

 
I hope, this article was helpful. Thank you for enduring it until the end. If you have any comments or questions then as always, I would love to hear them.