Image Slider

Concepts Used: show/hide, animations, selectors

Features:

  • Next/Prev buttons
  • Auto slideshow
<!DOCTYPE html>
<html>
<head>
  <title>Image Slider</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <style>
#slider { width: 400px; height: 250px; overflow: hidden; position: relative; }
#slider img { width: 400px; height: 250px; display: none; }
#slider img:first-child { display: block; }
.btn { cursor: pointer; margin: 5px; padding: 5px 10px; background: black; color: white; }
</style> </head> <body> <h2>Image Slider</h2> <div id="slider">
&lt;img src="https://via.placeholder.com/400x250/ff7f7f" /&gt;
&lt;img src="https://via.placeholder.com/400x250/7f7fff" /&gt;
&lt;img src="https://via.placeholder.com/400x250/7fff7f" /&gt;
</div> <button id="prev" class="btn">Prev</button> <button id="next" class="btn">Next</button> <script>
$(document).ready(function(){
  let index = 0;
  let images = $("#slider img");
  let total = images.length;
  function showImage(i){
    images.hide();
    images.eq(i).fadeIn();
  }
  $("#next").click(function(){
    index = (index + 1) % total;
    showImage(index);
  });
  $("#prev").click(function(){
    index = (index - 1 + total) % total;
    showImage(index);
  });
  // Auto Slide
  setInterval(function(){
    $("#next").click();
  }, 3000);
});
</script> </body> </html>

Explanation:

  • .eq(index) selects image by index.
  • .fadeIn() creates a smooth transition.
  • setInterval() automatically cycles through images.

Comments

Leave a Reply

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