I have an images carousel with prev and next arrows; i need to return to the first image when i arrive at the end of slides (to the last slide) and i click to the prev arrow.
This is my code:
<div class="container">
<div class="carousel">
<div class="slide one"></div>
<div class="slide two"></div>
<div class="slide three"></div>
<div class="slide four"></div>
<div class="slide five"></div>
<div class="slide six"></div>
</div>
</div>
<button class="prev"></button>
<button class="next"></button>
.container {
overflow-x: auto;
width: 100vw;
height: 100vh;
}
.carousel {
position: relative;
width: max-content;
}
.slide {
width: 25vw;
height: 100px;
border: 2px solid red;
margin: 0 1px;
float: left;
}
.next,
.prev {
width: 50px;
height: 50px;
position: absolute;
background: black;
top: 25px;
}
.next {
right: 0;
}
.prev {
left: 0;
}
var carousel = $('.carousel');
$('.next').on('click', function() {
carousel.animate({
left: '-=25vw'
}, 500);
});
$('.prev').on('click', function() {
carousel.animate({
left: ' =25vw'
}, 500);
});
This is a fiddle:
https://jsfiddle.net/9jweau4v/61/
Thank you.
CodePudding user response:
You can edit your js file as follows.
var carousel = $('.carousel');
var currentSlide = 0;
$('.next').on('click', function() {
if(currentSlide == $('.slide').length) {
carousel.animate({
left: '0'
}, 500);
currentSlide = 0
} else {
carousel.animate({
left: '-=25vw'
}, 500);
currentSlide = 1
}
});
$('.prev').on('click', function() {
if(currentSlide == 0) {
return
} else {
carousel.animate({
left: ' =25vw'
}, 500);
currentSlide -= 1
}
});
I added a if block to see if it's at the end of the list when showing the next image