'Zoom in and out of image on click using event listeners

I would like to create a function that takes in an array of images, checks whether an image has been clicked. If an image is clicked Zooms into the image, if the same image is clicked again, it would zoom out of the image.

This is what I have written

let imagesArr = document.querySelectorAll('img')
let isZoomed = false;
function rotateImage (e,isZoomed) {
    isZoomed = false ?
    e.forEach(function(item) {
        item.addEventListener('click', (event) => {
            item.style.transform = "scale(1.5)";
            event.stopImmediatePropagation();
        })
    }) : e.forEach(function(item) {
        item.addEventListener('click', (event) => {
            item.style.transform = "scale(1)";
            event.stopImmediatePropagation();
        })
    })
    isZoomed = true;
}
rotateImage(imagesArr,isZoomed);

I an trying to check whether the image is already zoomed (true, false) and zoom/zoom out based on this condition. Not getting an error, but my function does not work (nothing happens when I click an image)



Solution 1:[1]

You can add event listener in image that you want to zoom on click, and then in event listener you can add style property to for that perticular image!

Solution 2:[2]

  1. Delegate
  2. use a class

document.getElementById('container').addEventListener('click', function(e) {
  const tgt = e.target;
  tgt.classList.toggle('zoomed')
})
#container img.zoomed {
  transform: scale(1.5);
}
<div id="container"> 
  <img src="https://assets.stickpng.com/images/58afd6b70187e59a7d8a8f1c.png" />
  <img src="https://assets.stickpng.com/images/58afd6b70187e59a7d8a8f1c.png" />
  <img src="https://assets.stickpng.com/images/58afd6b70187e59a7d8a8f1c.png" />
</div>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Vinit Kasture
Solution 2 mplungjan