1
\$\begingroup\$

In the picture below, I want to open a modal when a user clicks anywhere within in the yellow block, including if they click on the white ‘+’ sign. The problem is, the click event happens on a different target depending on whether the user clicks on the yellow portion, or on the white ‘+’ sign.

In my JavaScript code, I have been handing it like this so far, but I wonder if there is a better, shorter way of doing this that doesn’t require the II operator:

function openModal(e) {
  if (e.target.classList.contains('project-box__picture-box') || e.target.classList.contains('project-box__icon')) {
    modalEl.classList.add('open');
  }
}

DOM Events

\$\endgroup\$
  • 1
    \$\begingroup\$ Welcome to code review! When posting code for review it helps to Add a relevant language tag (similar to your DOM tag) \$\endgroup\$ – DapperDan May 5 at 1:36
  • 1
    \$\begingroup\$ Welcome to Code Review! So that we can give you proper advice, please include your HTML as well. (Press Ctrl-M in the question editor to make a live demo.) \$\endgroup\$ – 200_success May 5 at 3:02
1
\$\begingroup\$

I can give you two ways to approach this: via JavaScript or CSS.

JavaScript

You can use the .closest() method of the HTMLElement interface. You need to pass it a CSS selector, and it will find you the closest DOM ancestor of the element that matches the given selector, or null if no such ancestor was found.

In this case, you could use it like this:

function openModal(e) {
  if (e.target.closest('.project-box__picture-box')) {
    modalEl.classList.add('open');
  }
}

(full method reference here)

CSS

The other option is to use the pointer-events CSS property. If you set this to none on all elements inside the clickable box, then those elements will not be allowed to be the targets of mouse events; instead, the target will be the closest ancestor that has pointer events enabled.

In this case, you'd need to add this CSS:

.project-box__picture-box * {
  pointer-events: none;
}

And this JS:

function openModal(e) {
  if (e.target.classList.contains('project-box__picture-box')) {
    modalEl.classList.add('open');
  }
}

(full property reference here)

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.