Home > Mobile >  Have click event go through an element without removing that element's pointer-event
Have click event go through an element without removing that element's pointer-event

Time:12-20

I have an absolute positioned div that is above another relative positioned div. They are both separate divs.

What I'm trying to do is: When I click on the absolute positioned div, I want to register that click and I want that click to go through it and register on the div below it.

Using CSS's pointer-events: none; on the top div doesn't work because then I will not be able to register a click on it.

Is this even posible?

In summary: I need a way to have an event go through an element without removing that element's event listener.

CodePudding user response:

You can do it nested and the bubbling will do it automatically.

https://javascript.info/bubbling-and-capturing

CodePudding user response:

When div#1 is clicked, you check if div#2 is under div#1 using elementsFromPoint method.
If yes, you create and dispatch another click event on div#2.

document.addEventListener('click', e => {
  console.log(e.target.id);
  if (e.target.id === 'one') {    
    const two = [...document.elementsFromPoint(e.clientX, e.clientY)]
                .find(el => el.id === 'two');

    if (two) {
      const clickEvent = document.createEvent('MouseEvents');
      clickEvent.initMouseEvent('click', !0, !0, window, 1, e.screenX, e.screenY, e.clientX, e.clientY, !1, !1, !1, !1, 0, null);
      two.dispatchEvent(clickEvent);
    }
  }
})
#one, #two {
position:absolute; z-index:0;
width:150px; height:150px;
background:#f009;
transform: rotateZ(30deg);
}

#two {
z-index:-1; left:100px;
background:#00f9;
transform:rotate(45deg);
}

/* ignore th following */
.as-console-wrapper {
left:50% !important; top:0; max-height:100% !important;
}
<div id="one"></div>
<div id="two"></div>

  • Related