How to create an automatic slideshow with HTML, CSS, and JS
What is an automatic slideshow?
This guide explains how to create an automatic image slideshow using HTML, CSS, and JavaScript. An automatic slideshow changes the image it displays after a set period.
A common use case of an automatic slideshow is in the hero section of a website. However, it can be used in any other section as well.
Steps for creating an automatic slideshow
We'll create an automatic slideshow in the following steps:
HTML code
CSS code
JavaScript code
HTML code
First, we write the HTML code to add the images.
Explanation
Line 3: We create a
divfor the images so that all images are contained within thatdiv.Lines 4–13: We create a separate
divfor each image. Within eachdiv, we then create theimgtag, which contains the link and description for each separate image of the slideshow.Line 14: We create the
scripttag just before the end of thebodytag to link the HTML file to the JavaScript file.
CSS code
Next, we write the CSS rules that add styling to the slideshow.
Explanation
Lines 1–3: We add the padding and border in the total width and height of all elements.
Lines 4–8: We set the maximum width of the
image-slideshowcontainer. We center the container holding the images and position it relative to its parent element.Lines 9–11: We create the
imgselector and give it a width of 100%.Lines 12–15: We create a fading animation for the images when the image changes. We set the animation duration to be 2 seconds.
Lines 16–19: We define how the opacity of the images change during the animation using the
@keyframesrule.
Enhance you understanding of HTML and its related concepts with the help of this project, Creating an Online CV with HTML and CSS.
JavaScript code
Lastly, we write the JavaScript code to ensure that the images change automatically.
Explanation
Line 3: We define an
indexvariable that lets us keep track of which image is currently being displayed.Line 4: We declare the
displayImages()function.Line 5: We define the
displayImages()function.Line 7: We select all the elements with the
imageclass and store them in animagesarray.Lines 8–10: We loop through all the elements in
imagesand hide them by setting theirdisplaystyle to “none.”Lines 12–14: We increment
indexby one and make sure that it stays within the range of 3 (the number of images).Line 15: We display only one image by setting its
displaystyle to “block.”Line 16: We call the
displayImages()function using thesetTimeout()function, which will execute the function after a 2,000 millisecond (2 seconds) delay.
Playground
Want to build a real-world application with HTML? Try this project, Build a Microblogging App Using PHP, HTML, JavaScript, and CSS.