outsideClick event?

Hello everyone!
There is a event or a way to activate a funcion when click any element except the element selected?.
I’m creating a image gallery:
CODEPEN: https://codepen.io/ricardorien/pen/ExZgpyQ?editors=0010
In Desktop mode (when you hover the image and you can see the blue layer) I want to close the Big Image when pressing out of that image, not by pressing the 'X Close" button.
There is a clean way to do this?

Thanks in advance!

document.addEventListener((event) => {
  if (event.target is NOT the element
  containing the image) {
    close
  }
}

ie if you click anywhere that isn’t that image popup, the popup closes. target is the element that caused the event. That includes any child elements by default (event bubbling), so if you had like

<figure class="image-popup">
  <img src="some-image.jpeg" />
  <figcaption>My Image</figcaption>
</figure>

Then

document.addEventListener((e) => {
  if (!e.target.classList.contains("image-popup") {
    // pseudo code:
    imagePopup.close();
  }
}

Should work, even if a user clicks on the image itself or the caption

2 Likes

Thanks! works as you say, this is a nice one to have it as a resource.
But my goal is to have the "display = ‘none’ " applied when clicked outside the image. It is not a whim, but I am interested to know, more for study purposes. I have read comments on StackOverflow but it really seems complex to achieve.

Another option you have with modal type elements is to expand the most outer container to take up the full height/width, that way you know what the click target will be outside the children.

In your case, you would need an extra element because you are using the container as an image frame with a white background and you likely want the most outer container to be transparent (or sometimes it will be a transparent color overlay).

Seconding what @lasjorg says, it’s the easiest thing to do to allow you to have the effect of darkening the screen when the modal pops up (you just have an element the size of the screen with a transparent dark background, then the modal is just a child element centred inside it)

Also, the way I described it, that’s literally how you do it: you want to act on clicks that aren’t on a specific element, so the way you do that is by acting on clicks that didn’t occur on that specific element. It’s not a trick, there isn’t a special way to do it that doesn’t involve acting on clicks outside the element. The browser JavaScript API doesn’t provide a function for that because there’s no point. If you want to apply display:none when you click outside the image, then just apply display:none in a version of the code I posted, you don’t have to do anything else.