Here is a short function that enlarges an image on click. Everything works fine when I only use one image. Adding a second image, it doesn’t work anymore and I have no clue why.
jQuery:
var classes = ["zoom0", "zoom50", "zoom100"];
var index = 0;
var classList = document.querySelector(".bla").classList;
const len = classes.length;
$('.zoom-img').click(function() {
classList.replace(classes[index++ % len], classes[index % len]);
});
HTML:
<!--This works-->
<div class="zoom-img">
<div class="zoom0 bla">
<img src="https://img.lemde.fr/2022/09/27/468/0/2800/1400/1600/800/60/0/4a83504_1664286495065-113206.jpg">
</div></div>
<!--This does not-->
<div class="zoom-img">
<div class="zoom0 bla">
<img src="https://img.lemde.fr/2022/09/27/468/0/2800/1400/1600/800/60/0/4a83504_1664286495065-113206.jpg">
</div></div>
2
Answers
Move the assignment of
classList
inside the
.click(function() {})
.First,
querySelector
will get the firstbla
element, that’s why only the first image gets zoomed, you need to get thebla
element inside each image container, so set it inside theclick
handler and set thequerySelector
of thecurrentTarget
.Second, each image should have it’s own
index
of zoom list, so, you need to get theclassName
of thebla
element and find the currentzoom
, and make the calculation depend on it.