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">
<img src="https://via.placeholder.com/400x250/ff7f7f" />
<img src="https://via.placeholder.com/400x250/7f7fff" />
<img src="https://via.placeholder.com/400x250/7fff7f" />
</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.
Leave a Reply