Simple Image Slider In JavaScript

<!DOCTYPE html>
<html lang="en">
<head>
  <!-- Character encoding -->
  <meta charset="UTF-8">

  <!-- Page title -->
  <title>Simple Image Slider</title>

  <style>
    /* Page styling */
    body {
      font-family: Arial, sans-serif;
      background: #f4f4f4;
      text-align: center;
      padding: 40px;
    }

    /* Slider container */
    .slider {
      background: white;
      padding: 20px;
      max-width: 400px;
      margin: auto;
      border-radius: 8px;
    }

    /* Image styling */
    img {
      width: 100%;
      border-radius: 5px;
    }

    /* Button styling */
    button {
      margin: 10px;
      padding: 10px 15px;
      cursor: pointer;
    }
  </style>
</head>

<body>

  <!-- Main slider box -->
  <div class="slider">

    <!-- Title -->
    <h2>Image Slider</h2>

    <!-- Image element (source will change with JavaScript) -->
    <img id="sliderImage" src="" alt="Slider Image">

    <!-- Navigation buttons -->
    <div>
      <button onclick="prevImage()">Previous</button>
      <button onclick="nextImage()">Next</button>
    </div>

  </div>

  <script>
    // Array holding image URLs
    const images = [
      "https://picsum.photos/400/250?random=1",
      "https://picsum.photos/400/250?random=2",
      "https://picsum.photos/400/250?random=3"
    ];

    // Keeps track of which image is currently shown
    let currentIndex = 0;

    // Get the image element from HTML
    const sliderImage = document.getElementById("sliderImage");

    // Show the first image when page loads
    sliderImage.src = images[currentIndex];

    // Function to show next image
    function nextImage() {
      // Move to next index
      currentIndex++;

      // If index goes past last image, go back to first
      if (currentIndex >= images.length) {
        currentIndex = 0;
      }

      // Update image source
      sliderImage.src = images[currentIndex];
    }

    // Function to show previous image
    function prevImage() {
      // Move to previous index
      currentIndex--;

      // If index goes below 0, go to last image
      if (currentIndex < 0) {
        currentIndex = images.length - 1;
      }

      // Update image source
      sliderImage.src = images[currentIndex];
    }
  </script>

</body>
</html>

Leave a Reply

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