Basic Image Slider Code Example

Table of Contents

Here’s an example of a basic image slider using HTML, JavaScript and CSS.


The HTML creates a container for the slider and individual slide elements for each image.

					<div class="slider">
  <div class="slide"><img decoding="async" src="image1.jpg" alt="image1"></div>
  <div class="slide"><img decoding="async" src="image2.jpg" alt="image2"></div>
  <div class="slide"><img decoding="async" src="image3.jpg" alt="image3"></div>



The JavaScript controls the functionality of the slider, including advancing through the slides, displaying the current slide, and hiding the other slides.

					var slideIndex = 1;

function plusSlides(n) {
  showSlides(slideIndex += n);

function currentSlide(n) {
  showSlides(slideIndex = n);

function showSlides(n) {
  var i;
  var slides = document.getElementsByClassName("slide");
  if (n > slides.length) {slideIndex = 1}    
  if (n < 1) {slideIndex = slides.length}
  for (i = 0; i < slides.length; i++) {
      slides[i].style.display = "none";  
  slides[slideIndex-1].style.display = "block";  



The CSS styles the container and the slide elements so that they fill the available space and center the images.

					.slider {
  width: 100%;
  overflow: hidden;

.slide {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;

.slide img {
  width: 100%;


This code uses a combination of HTML, CSS, and JavaScript to create a basic image slider.

Please note that this is a basic example, you can use this as a starting point and add more functionality to it as per your requirement


Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top