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.
html,
body {
height: 100%;
}
svg {
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
pointer-events:none;
}
svg *{
pointer-events:auto;
}
<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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With