One issue I'm facing is that on my page, I have multiple carousel rows. However, when I click on the "next" or "prev" button to navigate through the items in the carousel, it affects all carousels instead of just the one I clicked on.
I've attempted to separate them into partial views so that each JavaScript is executed only within its context, but the problem still persists.
My goal is to be able to navigate to the next and previous items independently of each other.
If possible, I'd like the JavaScript to only target items within the partial view. However, I'm open to considering other solutions as well.
Here is the JavaScript code:
$(document).ready(function () {
const multipleItemCarousel = document.querySelector('#carouselExample')
if (window.matchMedia('(min-width: 576px)').matches) {
const carousel = new bootstrap.Carousel(multipleItemCarousel, {
interval: false
})
var carouselWidth = $('.carousel-inner')[0].scrollWidth;
var cardWidth = $('.carousel-item').width();
var scrollPosition = 0;
$('.carousel-control-next').click(function () {
if (scrollPosition < carouselWidth - (cardWidth * 4)) {
scrollPosition += cardWidth;
$('.carousel-inner').animate(
{ scrollLeft: scrollPosition },
600
);
}
});
$('.carousel-control-prev').click(function () {
if (scrollPosition > 0) {
scrollPosition -= cardWidth;
$('.carousel-inner').animate(
{ scrollLeft: scrollPosition },
600
);
}
});
}
else {
$(multipleItemCarousel).addClass('slide');
}
});
This is the HTML code:
<div id="carouselExample" class="carousel">
<div class="carousel-inner">
<div class="carousel-item active">
<div class="card">
@{
var firstCourse = Model.First();
<img src="@firstCourse.Image" class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">@firstCourse.Title</h5>
<h6 class="card-subtitle mb-2 text-muted">Card subtitle</h6>
<p class="card-text">@firstCourse.Description</p>
<a href="#" class="card-link">Card link</a>
<a href="#" class="card-link">Another link</a>
</div>
}
</div>
</div>
@foreach (var course in Model.Skip(1))
{
<div class="carousel-item">
<div class="card">
<img src="@course.Image" class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">@course.Title</h5>
<h6 class="card-subtitle mb-2 text-muted">Card subtitle</h6>
<p class="card-text">@course.Description</p>
<a href="#" class="card-link">Card link</a>
<a href="#" class="card-link">Another link</a>
</div>
</div>
</div>
}
</div>
<button class="carousel-control-prev" type="button" data-bs-target="#carouselExample" data-bs-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="visually-hidden">Previous</span>
</button>
<button class="carousel-control-next" type="button" data-bs-target="#carouselExample" data-bs-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="visually-hidden">Next</span>
</button>
</div>
https://i.sstatic.net/c9lxc.jpg
The HTML code has been included for reference.