1

I have an SVG which I am trying to use as a navigation of some sort by using jQuerys click event.

The SVG has several groups which ahve various paths and text within. When clicking directly on a line/path/text the event is triggered however when clicking on transparent areas it is not triggered despite still being the group. Any suggestions on how to target the whole area?

Example Fiddle: If you click within the square or directly on the line it will fire but if you click between the square and line it will not

https://jsfiddle.net/benhnoou/96q1beu8/2/

jQuery:

$( "#diag-diagnosis" ).click(function() { 
    alert('diagnosis');
});

SVG Code:

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 240.5 200">
  <defs>
    <style>
      .cls-1 {
        fill: #fff;
      }

      .cls-2 {
        fill: none;
        stroke: #000;
        stroke-miterlimit: 10;
        stroke-width: 4px;
      }
    </style>
  </defs>
  <title>Asset 1</title>
  <g id="Layer_2" data-name="Layer 2">
    <g id="Layer_1-2" data-name="Layer 1">
      <g id="diag-diagnosis">
        <g>
          <rect class="cls-1" x="0.5" y="0.5" width="201" height="199"/>
          <path d="M201,1V199H1V1H201m1-1H0V200H202V0Z"/>
        </g>
        <line class="cls-2" x1="238.5" y1="16.5" x2="238.5" y2="167.5"/>
      </g>
    </g>
  </g>
</svg>
Ben H
  • 502
  • 1
  • 7
  • 24

2 Answers2

3

You might want to check out pointer-events from SVG2. The bounding-box property of pointer-events applies to groups as well as shapes. So this should make the transparent area between the two objects clickable.

$("#diag-diagnosis").click(function() {
  alert('diagnosis');
});
#diag-diagnosis {
  pointer-events: bounding-box;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 240.5 200">
  <defs>
    <style>
      .cls-1 {
        fill: #fff;
      }

      .cls-2 {
        fill: none;
        stroke: #000;
        stroke-miterlimit: 10;
        stroke-width: 4px;
      }
    </style>
  </defs>
  <title>Asset 1</title>
  <g id="Layer_2" data-name="Layer 2">
    <g id="Layer_1-2" data-name="Layer 1">
      <g id="diag-diagnosis">
        <g>
          <rect class="cls-1" x="0.5" y="0.5" width="201" height="199"/>
          <path d="M201,1V199H1V1H201m1-1H0V200H202V0Z"/>
        </g>
        <line class="cls-2" x1="238.5" y1="16.5" x2="238.5" y2="167.5"/>
      </g>
    </g>
  </g>
</svg>
JoshG
  • 6,472
  • 2
  • 38
  • 61
  • This doesn't seem to work in firefox but solid in Chrome. So far I figured I could just use a transparent shape over the clickable elements and target them instead – Ben H Jul 16 '19 at 08:58
  • Yeah, unfortunately `pointer-events` appears to be something in Firefox that have not (yet) been addressed: https://bugzilla.mozilla.org/show_bug.cgi?id=945187. – JoshG Jul 16 '19 at 09:05
0

Try to wrap it with tag

jsfiddle example

<a><svg></svg></a>
erani_246
  • 225
  • 4
  • 16