Slideshows are a great way to display images and a short blurb related to that, in an organized fashion. They are sometimes referred to as sliders, carousels, or image sliders.
A few use cases of a slideshow
- On the home page to display a few important features of the website.
- To organize work in your portfolio.
- To showcase the latest blog posts.
- To display the upcoming events.
There are several plugins in the market to create a slideshow. Often they clog your website with extraneous HTML in order to cover several use cases. In the example below, I used vanilla Javascript to create a simple slideshow with no plugins.
Steps to create a slideshow using Vanilla Javascript
- Load all the images into an array.
- Call the setInterval method every 3 ms which calls a custom function.
- In the function, load the image from the array and set as an attribute for the DOM image element.
- Use the ‘clearInterval’ method on the click event of the Image to clear the Timer.
A sampling of the code.
var imageArray=["images/slide1.jpg","images/slide2.jpg","images/slide3.jpg","images/slide4.jpg","images/slide5.jpg","images/slide6.jpg"]
var imageCounter=0;
var imageElement=document.getElementById("slImage");
function changeImage(){
imageElement.setAttribute("src",imageArray[imageCounter]);
imageCounter++;
if (imageCounter >= imageArray.length){
imageCounter=0;
}
}
var intervalHandle=setInterval(changeImage, 3000);
imageElement.onclick=function(){
clearInterval(intervalHandle);
}