Skip to content
Home » Forum

Forum

Image Carousel (Usi...
 
Notifications
Clear all

Image Carousel (Using Click Events)

1 Posts
1 Users
0 Reactions
68 Views
Mark Sikaundi
(@emmanuelmark117)
Member Admin
Joined: 2 years ago
Posts: 101
Topic starter  

Build an image slider where users can click "next" or "previous" buttons to cycle through images.

Use Case: Image Slider

Create a simple image carousel with "Next" and "Previous" buttons that navigate through images.

Example:

<img id="carousel" src="image1.jpg" alt="Image Carousel" width="400px" />
<button id="prev">Previous</button>
<button id="next">Next</button>

<script>
  const images = ['image1.jpg', 'image2.jpg', 'image3.jpg'];
  let currentIndex = 0;
  const carousel = document.getElementById('carousel');

  document.getElementById('next').addEventListener('click', function() {
    currentIndex = (currentIndex + 1) % images.length;
    carousel.src = images[currentIndex];
  });

  document.getElementById('prev').addEventListener('click', function() {
    currentIndex = (currentIndex - 1 + images.length) % images.length;
    carousel.src = images[currentIndex];
  });
</script>

   
Quote
Share: