I am working on jQuery carousel. Here is my code:
// CAROUSEL
$('#left-arrow').click(previousSlide);
$('#right-arrow').click(nextSlide);
function nextSlide() {
var $currentSlide = $('#carousel .slide-image:first');
var width = $currentSlide.width();
var $lastSlide = $('#carousel .slide-image:last')
$currentSlide.animate({ 'margin-left': -width }, 1000, function() {
$currentSlide.remove().css({ 'margin-left': '0px' });
$lastSlide.after($currentSlide);
});
}
function previousSlide() {
var $currentSlide = $('#carousel .slide-image:first');
var width = $currentSlide.width();
var $last = $('#carousel .slide-image:last');
$last.remove().css({ 'margin-left': -width });
$currentSlide.before($last);
$last.animate({ 'margin-left': '0px' }, 1000);
}
/* CAROUSEL */
#slide1 {
background-color: red;
}
#slide2 {
background-color: blue;
}
#slide3 {
background-color: magenta;
}
#carousel {
overflow: hidden;
white-space: nowrap;
position: relative;
width: 100vw;
height: 75vh;
}
.slide-image {
width: 100vw;
height: 75vh;
background-position: center;
background-size: cover;
display: inline-block;
}
.arrow {
width: 2%;
position: absolute;
top: 50%;
transform: translateY(-50%);
cursor: pointer;
}
#right-arrow {
right: 30px;
}
#left-arrow {
left: 30px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<section id="carousel">
<div class="arrow" id="left-arrow">L</div>
<div class="arrow" id="right-arrow">R</div>
<div class="slide-image" id="slide1">
</div>
<div class="slide-image" id="slide2">
</div>
<div class="slide-image" id="slide3">
</div>
</section>
The problem is that it is acting differently for left and right side. If you click left side multiple times, it will just move the slider number of times, according on the number of clicks at once. If you however click multiple times on the right side, it will always move only once. That is because the current slide is being pushed before the last slide and there is no slide yet. However I would like it to act the same as the left side so it should be able to move multiple times.
How could I achieve that behaviour?