Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Mouse Events through SVG Background

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.

like image 473
Robert Lord Avatar asked Oct 02 '17 22:10

Robert Lord


1 Answers

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>
like image 96
joopmicroop Avatar answered Nov 03 '22 01:11

joopmicroop