I have a Slider object which contains SliderImageUrl for the image.
Here is my c# code to show the slider list in HTML part.
ViewBag.Slider = db.Slider.ToList().OrderByDescending(x => x.SliderId);
I want to change a background image when I click the previous or forward button in the carousel.
I write a template js code to handle with it but I have no idea about other things.
How can I handle with this process?
Here is my HTML
code which is shown below.
<section id="hero" class="d-flex justify-cntent-center align-items-center">
<div id="heroCarousel" class="container carousel carousel-fade" data-bs-ride="carousel" data-bs-interval="5000">
@foreach (var item in @ViewBag.Slider)
{
<div class="carousel-item">
<div class="carousel-container">
<h2 class="animate__animated animate__fadeInDown">@item.SliderAd</h2>
<p class="animate__animated animate__fadeInUp">@item.SliderKisaAciklama</p>
<a href="#lastnews" class="btn-get-started animate__animated animate__fadeInUp">Sayfaya Git</a>
</div>
</div>
}
<a id="previous_button" class="carousel-control-prev" href="#heroCarousel" role="button" data-bs-slide="prev">
<span class="carousel-control-prev-icon bx bx-chevron-left" aria-hidden="true"></span>
</a>
<a id="forward_button" class="carousel-control-next" href="#heroCarousel" role="button" data-bs-slide="next">
<span class="carousel-control-next-icon bx bx-chevron-right" aria-hidden="true"></span>
</a>
</div>
</section>
Here is my javascript
code which is shown below.
<script>
$(document).ready(function () {
var myArray = [];
@foreach (var item in @ViewBag.Slider)
{
@:myArray.push(item);
}
var el = document.getElementById("previous_button");
if (el) {
addEventListener("click", switchImage1());
}
var el2 = document.getElementById("forward_button");
if (el2) {
addEventListener("click", switchImage2());
}
});
function switchImage1(imageUrl) {
$('#hero').css('background-image', "url('+ imageUrl +')");
}
function switchImage2(imageUrl) {
$('#hero').css('background-image', "url('+ imageUrl +')");
}
</script>
Here is the solution which is shown below.
$('#hero').css('background-image', "url(" + $(".carousel-item:eq(0)").data("image") + ")");
$("#heroCarousel").on('slide.bs.carousel', function () {
$('#hero').css('background-image', "url(" + $(".carousel-item.active").data("image") + ")");
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.