Javascript

jQuery Image Carousel

️ Simple jQuery Image Carousel

HTML

html
<div id="carousel">
<div class="slides">
<img src="img1.jpg" class="active" alt="Slide 1" />
<img src="img2.jpg" alt="Slide 2" />
<img src="img3.jpg" alt="Slide 3" />
</div>
<button id="prev">Prev</button>
<button id="next">Next</button>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>


CSS

html
<style>
#carousel {
position: relative;
width: 600px;
height: 400px;
margin: auto;
overflow: hidden;
}

.slides img {
position: absolute;
width: 100%;
height: 100%;
display: none;
object-fit: cover;
}

.slides img.active {
display: block;
}

#prev, #next {
position: absolute;
top: 50%;
transform: translateY(-50%);
background: rgba(255,255,255,0.7);
border: none;
padding: 10px 15px;
cursor: pointer;
font-size: 16px;
}

#prev { left: 10px; }
#next { right: 10px; }
</style>


jQuery Script

js
$(document).ready(function() {
let currentIndex = 0;
const slides = $('#carousel .slides img');
const totalSlides = slides.length;

function showSlide(index) {
slides.removeClass('active').fadeOut(500);
slides.eq(index).addClass('active').fadeIn(500);
}

$('#next').click(function() {
currentIndex = (currentIndex + 1) % totalSlides;
showSlide(currentIndex);
});

$('#prev').click(function() {
currentIndex = (currentIndex - 1 + totalSlides) % totalSlides;
showSlide(currentIndex);
});

// Initialize first slide
showSlide(currentIndex);
});


How it works:

  • All images are stacked on top of each other (absolute positioning).

  • Only the active slide is visible (displayed and faded in).

  • Clicking next/prev buttons cycles through the images with a fade effect.

Leave a Reply

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