I have two SVG elements, each covering the entire screen.
html,
body {
height: 100%;
}
svg {
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
}
<body>
<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%">
<rect x=0 y=0 width=50 height=50 fill='#ff0000' onclick="console.log(1)"></rect>
</svg>
<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%">
<rect x=40 y=40 width=50 height=50 fill='#00ff00' onclick="console.log(2)"></rect>
</svg>
</body>
Even though the squares are not overlapping, click events will never be passed to the red square, since the SVG with the green square covers the whole screen and captures any click events. Is there any way to have click events on both of these squares, without them being in the same SVG?
A solution like How can I pass ONLY clicks through a SVG with pointer-events? is great at passing click events through to the red square, but only if you're okay with discarding all events on the green square.
Just add pointer-events none to the svg tag. And on everything else inside the svg add pointer-events auto. Making only the elements inside the svg clickable, not the parent svg tag.
Works in chrome.
Wrap your svg elements with another svg element. See here why this works: If an
<svg>
element is not the outermost, it cannot be the target of pointer events. The outermost here is part of a HTML context, so it acts like a<div>
.