Image slider using HTML CSS and JavaScript
<!DOCTYPE html>
<html>
<head>
<title>Image Slider with Buttons</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin: 0;
padding: 0;
}
.slider {
width: 600px;
height: 300px;
margin: 20px auto;
border: 2px solid #ccc;
overflow: hidden;
position: relative;
}
.slider img {
width: 100%;
height: 100%;
display: none; /* Hide all images by default */
}
.slider img.active {
display: block; /* Show only the active image */
}
.buttons {
margin-top: 10px;
}
.buttons button {
padding: 10px 20px;
margin: 0 5px;
font-size: 16px;
cursor: pointer;
}
</style>
</head>
<body>
<h1>Image Slider with Buttons</h1>
<div class="slider">
<img src="https://via.placeholder.com/600x300/FF5733/FFFFFF?text=Image+1" class="active" alt="Image 1">
<img src="https://via.placeholder.com/600x300/33FF57/FFFFFF?text=Image+2" alt="Image 2">
<img src="https://via.placeholder.com/600x300/5733FF/FFFFFF?text=Image+3" alt="Image 3">
</div>
<div class="buttons">
<button onclick="showPrevious()">Previous</button>
<button onclick="showNext()">Next</button>
</div>
<script>
let currentIndex = 0;
const images = document.querySelectorAll(".slider img");
function showImage(index) {
// Hide all images
images.forEach(img => img.classList.remove("active"));
// Show the desired image
images[index].classList.add("active");
}
function showNext() {
currentIndex = (currentIndex + 1) % images.length; // Loop to the first image
showImage(currentIndex);
}
function showPrevious() {
currentIndex = (currentIndex - 1 + images.length) % images.length; // Loop to the last image
showImage(currentIndex);
}
</script>
</body>
</html>
Explanation:
HTML Structure:
- The slider contains multiple
<img>
tags. - A Previous and Next button are added below the slider.
- The slider contains multiple
CSS Styling:
- Images are hidden by default (
display: none
). - Only the image with the
active
class is shown (display: block
).
- Images are hidden by default (
JavaScript Logic:
showImage(index)
: Displays the image corresponding to the given index.showNext()
: Increases the index and loops to the first image when the end is reached.showPrevious()
: Decreases the index and loops to the last image if the index becomes negative.- The buttons trigger these functions using the
onclick
attribute.
Note: change the img with your own images.
Comments
Post a Comment