How to create a simple slider with CSS and jQuery?

by phayes0289

HTML

<div id="slides">
    <div class="slide show"><img src="https://images.pexels.com/photos/1447092/pexels-photo-1447092.png?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260" alt="view-of-rice-terraces"></div>
    <div class="slide">Text Slide: Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quasi, qui aut repudiandae
      minus quas ex tenetur consectetur nostrum dolorem iusto accusamus sint culpa quae, impedit vel earum. Nihil, qui
      saepe.</div>
    <div class="slide">another text slide</div>
    <div class="slide"><img src="https://images.pexels.com/photos/709552/pexels-photo-709552.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260" alt="body-of-water-between-green-leaf-trees"></div>
    <div class="slide">last slide</div>
  </div>


  <p style="position:absolute;bottom:0;right:0">This fiddle is a part of a <a href="https://www.yogeshchauhan.com/how-to-create-a-simple-slider-with-css-and-jquery/" target="_blank">Blog Post on YogeshChauhan.com</a></p>

CSS

* {
  box-sizing: border-box;
  margin: 0;
}

#slides {
  position: relative;
  height: 300px;
}

.slide {
  position: absolute;
  left: 0px;
  top: 0px;
  width: 100%;
  height: 100%;
  font-size: 2rem;
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
}

img {
  height: 100%;
  width: 100%;
  object-fit: cover;
}

JavaScript

$("#slides").children().hide();
$("#slides div:nth-child(1)").show();

var i = 1;
var allChildren = $("#slides").children().length;

setInterval(function() {
  $("#slides div:nth-child(" + i + ")").hide();
  i++;
  if (i == allChildren + 1) {
    i = 1;
  }
  $("#slides div:nth-child(" + i + ")").show();
}, 5000);