This HTML CSS & JavaScript code snippet helps you to create an automatic image slider/slideshow. It initializes variables for the index, slide elements, and dot elements. The changeSlide
function updates the slide and dot display after a certain time.
It uses a loop to hide all the slides and remove the “active” class from all the dots before showing the current slide and adding the “active” class to the corresponding dot. The setTimeout
method is used to call the changeSlide
function every 2 seconds.
How to Create an Automatic Image Slider in HTML CSS and JavaScript
First of all, create a div element with a class name “slider” and add your images inside it wrapping it with a div tag with the class attribute of “slides”. You can add multiple images by following the same method as given below:
<span id="heading">Simple automatic slider</span> <div id="slider"> <div class="slides"> <img src="path/to/image.jpg" width="100%" /> </div> <div class="slides"> <img src="path/to/image.jpg" width="100%" /> </div> <div class="slides"> <img src="path/to/image.jpg" width="100%" /> </div> <div class="slides"> <img src="path/to/image.jpg" width="100%" /> </div> <div class="slides"> <img src="path/to/image.jpg" width="100%" /> </div> <div id="dot"><span class="dot"></span><span class="dot"></span><span class="dot"></span><span class="dot"></span><span class="dot"></span></div> </div>
Now, style the image slider using the following CSS rules. You can change the CSS values in order to customize the image slider according to your needs.
*{ margin:0; padding:0; box-sizing:border-box; } @keyframes fade{ from{ opacity:0.4; } to{ opacity:1; } } body{ background:#eeeee; } #slider{ margin:0 auto; width:80%; overflow:hidden; } .slides{ overflow:hidden; animation-name:fade; animation-duration:1s; display:none; } img{ width:100%; } #dot{ margin:0 auto; text-align:center; } .dot{ display:inline-block; border-radius:50%; background:#d3d3d3; padding:8px; margin:10px 5px; } .active{ background:black; } @media (max-width:567px){ #slider{ width:100%; } } #heading{ display:block; text-align:center; font-size:2em; margin:10px 0px; }
Finally, add the following JavaScript function to activate the image slider. If you want to change the automatic sliding time for the images, you can set the custom time duration (in milliseconds) inside the setTimeout function.
var index = 0; var slides = document.querySelectorAll(".slides"); var dot = document.querySelectorAll(".dot"); function changeSlide(){ if(index<0){ index = slides.length-1; } if(index>slides.length-1){ index = 0; } for(let i=0;i<slides.length;i++){ slides[i].style.display = "none"; dot[i].classList.remove("active"); } slides[index].style.display= "block"; dot[index].classList.add("active"); index++; setTimeout(changeSlide,2000); } changeSlide();
That’s all! hopefully, you have successfully created an automatic image slider. If you have any questions or suggestions, feel free to comment below.