I created a slideshow that toggles before and after images on click. I'm trying to also get the caption for each image to simultaneously change with each click. It works on each individual image, but when the user moves to the next slide the text stays in the state it was for the previous slide. So even though all the slides start out using the before images, if user progresses to the next slide when the text reads "After", it continues to read "After".
<div class="carousel-inner">
<div class="item active">
<img src="imgs/retouched/tattoo_before.jpg" onclick="diffImage1(this)">
<div class="carousel-caption"><p>Before</p></div>
</div>
<div class="item">
<img src="imgs/retouched/rings_before.jpg" onclick="diffImage2(this)">
<div class="carousel-caption"><p>Before</p></div>
</div>
<div class="item">
<img src="imgs/retouched/pistol_before.jpg" onclick="diffImage3(this)">
<div class="carousel-caption"><p>Before</p></div>
</div>
</div>
Please let me know a more condensed way of writing these functions if possible. (I imagine there must be a way to write it in one function). I tried also writing a new function just to change the text, as it is the same for each image, but I had the same problem:
function diffImage1(img) {
if (img.src.match("_before")) {
img.src = "imgs/retouched/tattoo_after.jpg";
$(".carousel-caption p").html("After");
} else {
img.src = "imgs/retouched/tattoo_before.jpg";
$(".carousel-caption p").html("Before");
}
}
function diffImage2(img) {
if (img.src.match("_before")) {
img.src = "imgs/retouched/rings_after.jpg";
$(".carousel-caption p").html("After");
} else {
img.src = "imgs/retouched/rings_before.jpg";
$(".carousel-caption p").html("Before");
}
}
function diffImage3(img) {
if (img.src.match("_before")) {
img.src = "imgs/retouched/pistol_after.jpg";
$(".carousel-caption p").html("After");
} else {
img.src = "imgs/retouched/pistol_before.jpg";
$(".carousel-caption p").html("Before");
}
}
Combine them into a single function like this
$("div.carousel-inner div.item img").on("click", function(){
if ($(this).src.match("_before")) {
$(this).src = "imgs/retouched/pistol_after.jpg";
$(this).parent().find("p").html("After");
} else {
$(this).src = "imgs/retouched/pistol_before.jpg";
$(this).parent().find("p").html("Before");
}
}
You don't need onclick=
anymore on the img
s