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.
We'll create an automatic slideshow in the following steps:
HTML code
CSS code
JavaScript code
First, we write the HTML code to add the images.
Line 3: We create a div
for the images so that all images are contained within that div
.
Lines 4–13: We create a separate div
for each image. Within each div
, we then create the img
tag, which contains the link and description for each separate image of the slideshow.
Line 14: We create the script
tag just before the end of the body
tag to link the HTML file to the JavaScript file.
Next, we write the CSS rules that add styling to the slideshow.
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-slideshow
container. We center the container holding the images and position it relative to its parent element.
Lines 9–11: We create the img
selector 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 @keyframes
rule.
Enhance you understanding of HTML and its related concepts with the help of this project, Creating an Online CV with HTML and CSS.
Lastly, we write the JavaScript code to ensure that the images change automatically.
Line 3: We define an index
variable 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 image
class and store them in an images
array.
Lines 8–10: We loop through all the elements in images
and hide them by setting their display
style to “none.”
Lines 12–14: We increment index
by 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 display
style to “block.”
Line 16: We call the displayImages()
function using the setTimeout()
function, which will execute the function after a 2,000 millisecond (2 seconds) delay.
Want to build a real-world application with HTML? Try this project, Build a Microblogging App Using PHP, HTML, JavaScript, and CSS.