Image Slider (JS Mini Project) By Rupen Prasai

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="styles.css">
    <title>Image slider</title>
</head>
<body>
    <h1>Image Slider</h1>
    <div class="slider">
        <div class="slides">
          <img src="image1.JPG" alt="Image 1">
          <img src="image2.jpg" alt="Image 2">
          <img src="image3.JPG" alt="Image 3">
        </div>
        <button class="prev" onclick="changeSlide(-1)">Previous</button>
        <button class="next" onclick="changeSlide(1)">Next</button>
      </div>
      <script src="script.js"></script>
</body>
</html>

style.css

.slider {
    position: relative;
    max-width: 800px;
    margin: auto;
  }
  
  .slides {
    display: flex;
    overflow-x: hidden;
    width: 500px;
    height: 300pxs;
  }
  h1{
    text-align: center;
  }

  .slides img {
    width: 100%;
    display: block;
  }
  
  button {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    padding: 10px;
    background-color: #333;
    color: #fff;
    border: none;
    cursor: pointer;
  }
  
  .prev {
    left: 0;
  }
  
  .next {
    right: 0;
  }

script.js

let slideIndex = 1;
showSlide(slideIndex);

function changeSlide(n) {
  showSlide(slideIndex += n);
}

function showSlide(n) {
  const slides = document.getElementsByClassName("slides")[0].getElementsByTagName("img");
  if (n > slides.length) {
    slideIndex = 1;
  }
  if (n < 1) {
    slideIndex = slides.length;
  }
  for (let i = 0; i < slides.length; i++) {
    slides[i].style.display = "none";
  }
  slides[slideIndex - 1].style.display = "block";
}