Allow one zoomed image at a time

Viewed 475

I am using a fairly nice zoom-in / zoom-out effect using only CSS and HTML. The issue I am having is that if a user zooms in on two images, both images will be enlarged on the page. This is technically what it should do, however I am wondering how I can disable this effect.

This is what I am looking for: e.g. there are two images on a page. If I zoom in one one image and then zoom in on the other image (while the first image is zoomed), the first image should zoom out to allow the second image to be the only zoomed image on the page. This principle would apply if there were, for example, ten images -- only one image can be zoomed at any time.

input[type=checkbox] {
display: none;
}

.container img {
width: 100%;
transition: transform 0.25s ease;
cursor: zoom-in;
}

input[type=checkbox]:checked ~ label > img {
transform: scale(2.5);
cursor: zoom-out;
}
<div class="container">
    <input type="checkbox" id="zoomCheck1">
    <label for="zoomCheck1">
    <img src="https://www.vintagevelo.co.uk/wp-content/uploads/2018/02/DSC_0040-768x512.jpg" />
    </label>
</div>
<div class="container">
    <input type="checkbox" id="zoomCheck2">
    <label for="zoomCheck2">
    <img src="https://premium-cycling.com/wp-content/uploads/2018/05/FAGGIN-Campione-del-mondo-1980s-frameset-7.jpg" />
    </label>
</div>

1 Answers

Use the + single next selector instead of next all

Note: I recommend using more specific class selectors of some sort, so that these styles don't end up affecting other elements unintentionally, and make the styles more reusable.

Switched to radio elements to only allow one to be checked at a time. Use "name" to group them. You can also use name attribute for the selectors.

document.querySelector('.container').addEventListener('click', e => {
  if (e.target.matches('input[type=radio] + label > img')) {
    e.target.parentNode.previousSibling.previousSibling.checked = !e.target.parentNode.previousSibling.previousSibling.checked;
    e.preventDefault();
  }
});
input[type=radio] {
  display: none;
}

.container img {
  width: 100%;
  transition: transform 0.25s ease;
  cursor: zoom-in;
}

input[type=radio]:checked+label>img {
  transform: scale(2.5);
  cursor: zoom-out;
}

img {
  width: 50px!important;
  height: 50px;
}
<div class="container">
  <input type="radio" name="zooms" id="zoomCheck1">
  <label for="zoomCheck1">
    <img class="center round-corner" 
         src="https://i.imgur.com/8qmxbHT.jpeg" />
    </label>
  <input type="radio" name="zooms" id="zoomCheck2">
  <label for="zoomCheck2">
    <img class="center round-corner" 
         src="https://i.imgur.com/8qmxbHT.jpeg" />
    </label>
</div>

Related