Image Slider / Carousel

Why? Learn arrays, DOM manipulation, and auto-sliding with setInterval().

<!DOCTYPE html>
<html>
<head>
  <title>Image Slider</title>
  <style>
img { width: 400px; height: 250px; display: block; margin: auto; }
button { margin: 10px; padding: 10px; }
</style> </head> <body> <h2 style="text-align:center">Image Slider</h2> <img id="slider" src="https://picsum.photos/id/1011/400/250"> <div style="text-align:center">
&lt;button onclick="prev()"&gt;Prev&lt;/button&gt;
&lt;button onclick="next()"&gt;Next&lt;/button&gt;
</div> <script>
let images = &#91;
  "https://picsum.photos/id/1011/400/250",
  "https://picsum.photos/id/1015/400/250",
  "https://picsum.photos/id/1016/400/250",
  "https://picsum.photos/id/1025/400/250"
];
let index = 0;
function showImage() {
  document.getElementById("slider").src = images&#91;index];
}
function next() {
  index = (index + 1) % images.length;
  showImage();
}
function prev() {
  index = (index - 1 + images.length) % images.length;
  showImage();
}
setInterval(next, 3000); // auto change every 3 seconds
</script> </body> </html>

Explanation:

  • Images stored in an array.
  • next() & prev() update index and show image.
  • setInterval(next, 3000) auto-changes image every 3 seconds.

Comments

Leave a Reply

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