Click event outside image when using object-fit on img

Viewed 403

I suppose it's not possible, but want to double check: If I have an image that is object-fit:contain; and then click outside the image (on the background) but still inside the img frame - is there a way to let the click event bypass the img, just like if I had clicked outside the img frame?

Like so? thanks!

enter image description here

document.querySelector('.behind').addEventListener('click', e=> {
  alert('this will never happen :(')
})
body {
  margin:0;
}
img {
  width:100vw;
  height:100vh;
  object-fit:contain;
 
}
.behind {
  position:fixed;
  top:0;
  left:0;
  width:100%;
  height:100vh;
  background-color:red;
  z-index:-1;
}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>A Great Demo on CodePen</title>
</head>
<body>
  <div class="behind">
    
  </div>
  <div class="image">
        <img src="https://picsum.photos/600/600">
  </div>
  
</body>
</html>

1 Answers

Do it differently without object-fit

document.querySelector('.behind').addEventListener('click', e => {
  alert('this will never happen :(')
})
body {
  margin: 0;
}

img {
  max-width:100%;
  max-height:100vh;
  display:block;
  margin:auto;
  position: fixed;
  top: 0;
  left: 0;
  bottom:0;
  right:0;
}

.behind {
  width: 100%;
  height: 100vh;
  background-color: red;
  z-index: -1;
}
<div class="behind">

</div>
  <img src="https://picsum.photos/600/600">

Related