3

Let's assume I have two overlapping divs, and the following jQuery snippet:

$( "#div1" ).click(function() {
  console.log('click on div1');
});

$( "#div2" ).mousemove(function() {
  console.log('mousemove on div2');
});

As far as I understood, in this case only one div receives events - either the latest defined in the HTML, or with the highest z-index, div2 in my case.

By googling around I found out that events could be propagated to div1 if div2 is styled with pointer-events: none. This makes div2 completely unresponsive to any mouse events.

But would it be possible to have the events triggered on both divs? At least being able to filter out events (e.g. in the provided example, have mousemoves triggering div2 and clicks div1)?

The full example can be found here.

Pierrick Bruneau
  • 147
  • 1
  • 10
  • 2
    Can you make the second div a child of the first? If so, all click events on the child will propagate to the parent as well. But if the overlap is only partial, this would mean that even if you clicked an area of #div2 that didn't overlap #div1, #div1's events would still run. – Ben Oct 22 '14 at 18:42
  • This indeed works with divs, but in my actual project, the underlying element (ie the first) is a SVG - as far as I know, nesting HTML elements in a SVG is not supported in a straightforward maneer. But thanks for the comment anyway! – Pierrick Bruneau Oct 23 '14 at 06:50

1 Answers1

2

Yes, sort of, although its not terribly simple. You will have to use code in the event handler for each div that triggers the event the other is listening for. See Juan's answer to this question, the code he wrote can be generalized to other events.

Community
  • 1
  • 1
Jared Smith
  • 19,721
  • 5
  • 45
  • 83
  • Thanks for the suggestion, this will do the trick for my current problem - but as for Ben's solution above, partially overlapping elements are not correctly handled this way. For example, in my updated plunk, clicking on the pure green area on the left triggers the event for div1, but the latter is not actually under the pointer. This is rather an extension to the initial problem, but would there be a solution for the latter case? – Pierrick Bruneau Oct 23 '14 at 06:52
  • 1
    One way to solve the problem of partially overlapping objects would be to temporarily hide the topmost one, use `document.elementFromPoint(event.x,event.y)` to find the element beneath it, then see the returned element is a child of the one you care about. – Tesseract Dec 05 '20 at 07:05