Simple slider element with vanilla js and animation effects

purejsjavascripthtmlcssslider

Simple slider element with vanilla js and animation effects Tutorial by Mirko Zovko | 23. Jul. 2020.

Welcome to one more tutorial in series of creating simple elements with vanilla js.


In this tutorial I’ll show you how to create a very simple responsive slideshow (slider) in vanilla js. It doesn't have any special elements or features, only duration time and fade-in fade-out effect between images.

Html structure only contain 2 different element:

  • slider - is a container for all images that are going into the slider. This class is used for adding style on your slider so to start your slider it would be good beside this class to use an id or some unique class for every slider you are creating. Like that you can have multiple sliders per page.
  • Other elements are only images that are going into the slider, nothing else.

For style there are only a few things that I did but the most important one is transition time on img. I used 0.4s for transition and I’m taking that in calculation when creating js script for sliding. I’ll explain more about that part.


For starting the slider I used the initSlider function that have two parameters:

  • elem - unique class or id of a slider
  • duration - time between slides

In the first part of that function I’m going through all images and putting them to display none except for the first image on which I’m adding an active class to show it at the start.

Everything else is happening in the slideImage() function. I’m using the i variable to check what is the next image to slide. As I mentioned before, I’m using 0.4s as transition face effects, that’s why I’m waiting 0.4s before adding display none to the element, after the fade effect is done.

I’m not adding a display block and active class element to the image at the same time, I’m adding a display block, waiting or 50ms and then adding an active class. Doing it like that I notice that fade animation is much much better and smoother.

Try by yourself without timeout and you will notice the difference.


Full working code you can check on jsFiddle or on Codepen.




I hope you liked this article. If you have some suggestion or idea feel free to write in comment section bellow. Enjoy! :)