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">
<button onclick="prev()">Prev</button>
<button onclick="next()">Next</button>
</div>
<script>
let images = [
"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[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.
Leave a Reply