I am facing a challenge with creating a carousel of three images in HTML using jQuery. When the user clicks on the "Next" or "Previous" buttons, I want to scroll through the images one by one. However, I am struggling to hide the other images when one is displayed. If I only have one image in the carousel, it appears correctly styled, but adding the other two images and implementing the button scrolling feature has proven difficult.
Here is the HTML code:
<div class="wrapper">
<div class="container">
<div class="carouselWrapper">
<div class="carousel">
<div class="cImg active" >
<img src="../1.jpg">
</div>
<div class="cImg">
<img src="../2.jpg">
</div>
<div class="cImg">
<img src="../3.jpg">
</div>
</div>
<div id="nav">
<div id="button-previous">prev</div>
<div id="button-next">next</div>
</div>
</div>
And here is the jQuery code:
<script type="text/javascript">
$(document).ready(function(){
$('.active').show();
$('#button-next').click(function(){
$('.active').removeClass('active').addClass('oldActive');
if ($('.oldActive').is(':last-child')) {
$('.cImg').first().addClass('active');
} else {
$('.oldActive').next().addClass('active');
}
$('.oldActive').removeClass('oldActive');
$('.cImg').fadeOut();
$('.active').fadeIn();
});
$('#button-previous').click(function(){
$('.active').removeClass('active').addClass('oldActive');
if ($('.oldActive').is(':first-child')) {
$('.cImg').last().addClass('active');
} else {
$('.oldActive').prev().addClass('active');
}
$('.oldActive').removeClass('oldActive');
$('.cImg').fadeOut();
$('.active').fadeIn();
});
});
</script>
Lastly, here is the CSS code:
.carousel img {
float: left;
width: 40%;
height: auto;
margin: 20px 40px 80px 20px;
}