Reputation: 512
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>
Upvotes: 1
Views: 492
Reputation: 6735
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>
Upvotes: 3