javascript autoplay slider

Javascript Autoplay Slider

If you want to create an autoplay slider using Javascript, there are multiple ways to achieve this result. One of the most popular ways is to use jQuery plugins like Slick or Owl Carousel. However, in this tutorial, we will be using pure Javascript to create the slider.

HTML Markup

First, we need to create the HTML markup for the slider. We will create a div with a class name of "slider". Inside the slider div, we will create a div with a class name of "slide". This div will contain our images. Here's the code:


    <div class="slider">
      <div class="slide">
        <img src="image1.jpg" alt="Image 1">
      </div>
      <div class="slide">
        <img src="image2.jpg" alt="Image 2">
      </div>
      <div class="slide">
        <img src="image3.jpg" alt="Image 3">
      </div>
    </div>
  

CSS Styling

Next, we need to style our slider using CSS. We will use position relative for the slider div and position absolute for the slide div. We will also set the width and height of the slider and hide the overflow. Here's the code:


    .slider {
      position: relative;
      width: 800px;
      height: 500px;
      overflow: hidden;
    }

    .slide {
      position: absolute;
      top: 0;
      left: 0;
      width: 800px;
      height: 500px;
    }
  

Javascript Code

Finally, we need to write the Javascript code to make our slider autoplay. We will use setInterval to change the slide every 3 seconds. Here's the code:


    var slideIndex = 0;
    var slides = document.getElementsByClassName("slide");

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

    setInterval(showSlides, 3000);
  

Explanation:

  • First, we create a variable called "slideIndex" and set it to 0.
  • Next, we create a variable called "slides" and use the getElementsByClassName method to get all the elements with a class name of "slide".
  • We then create a function called "showSlides" which hides all the slides except for the current slide.
  • We then increment the slideIndex by 1 and check if it is greater than the number of slides. If it is, we reset it to 1.
  • Finally, we show the current slide by setting its display property to "block".
  • We use the setInterval method to call the showSlides function every 3 seconds, which creates an autoplay slider.

And that's it! You now have a simple Javascript autoplay slider. Of course, you can customize it further to fit your needs, such as adding navigation buttons or changing the speed of the autoplay.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe