How to Create a Slideshow

Set the slide index to 1 in JavaScript and display the image according to the index;

Hide all the images before displaying any image.

When the left and right arrows are clicked, change the index (left-1, right+1), when the index exceeds the total number of images, reset it to 1, and vice versa, and then execute the showSlides function.

To highlight the logic of creating a slideshow, I simplified the slideshow example by the W3Schools, removing things like gradient effects, captions, and the dot navigation, leaving only the most basic images and left and right arrows.

Firstly, let’s take look at the HTML. We have only a container, three pictures, and the left and right arrows:

In order to vertically center the two arrows, the position of the container was set to relative, so that it the container can be relative to the arrows inside (“An element with position: absolute; is positioned relative to the nearest positioned ancestor” —W3Schools). The top of the two arrows is set to 50%, so that the top of the arrow appears at the center of the picture, and then the arrows are moved up by the negative margin-top to make it in the middle of the height of the picture, so The negative value of the margin-top is about half of the height of the arrows. Finally, we move the right arrow to the right: right: 0;

The slideIndex is set to 1 at the beginning, and the showSlides function is executed immediately to display the first picture.

The changeSlides function is to execute showSlides with a new image index, used by the arrows as the event function.

The key is the showSlides function. Firstly, we get all the images with document.getElementsByClassName, and then we check whether the image index is out of range: less than 1 or greater than the total number of images, if so, reset the index. Next, we use the for loop to hide all the images. Finally, the image is displayed according to the index.

This is the essence of the slideshow. There are more features in the original W3Schools. If you can understand the logic here, I believe you can figure the rest easily.

W3Schools How-To Videos

W3Schools is a well-known web design/front-end development tutorial website, which not only provides detailed tutorials on HTML, CSS, JavaScript, etc., but also can be used as a reference, as it explains almost everything in the web design field. You probably have already visited this website as a frontend developer, because it often appears on the first page of many search results that are related to web design. And its How To section is really useful. It provides tutorials on, for example, how to make a SlideShow (picture carousel), a Lightbox, a Parallax effect and so on. So I want to do a series of videos dedicated to these How-Tos.