I'm trying to add click handlers to my svg. But the functions never trigger.
In my example I replaced the path of the svg because I couldn't upload it here. But the SVG file looks like this:
<?xml version="1.0" encoding="utf-8"?>
<svg version="1.1" id="Laag_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
viewBox="0 0 566.9 566.9" style="enable-background:new 0 0 566.9 566.9;" xml:space="preserve">
<g id="SvgKaart">
<style type="text/css">
.st0{fill:none;stroke:#010202;stroke-linejoin:round;stroke-miterlimit:10;}
.st1{fill:#5EBCA4;stroke:#010202;stroke-linejoin:round;stroke-miterlimit:10;}
.st2{fill:none;}
.st3{font-family:'Helvetica';}
.st4{font-size:29px;}
</style>
<polygon class="st0 regio-2 regio" points="133.3,165.3 108.7,124.7 108.7,80.7 121,72 138,58 158,50 176,50 184.7,60 190,70 192.7,78.7
192.7,95.3 188,104.7 186.7,112.7 184,121.3 180.7,130.7 173.3,139.7 170.7,151.3 164,156.3 153,165.7 146.7,169.3 "/>
<polygon class="st0 regio-2 regio" points="192.7,78.7 207,78.7 213,66.3 224,64.7 233.3,68.3 245,70 258.3,78.7 259.7,90.3 261.3,95.7 263.3,104
263.3,148 245,169.3 238.7,171 228,174.3 216.7,178 209,182.3 201,190.3 198.7,197.3 199.3,216.7 176.7,216.7 163.7,221.7
159.7,224 159.7,197.3 165.7,181.7 169.7,169.3 170.7,151.3 173.3,139.7 180.7,130.7 186.7,112.7 188,104.7 192.7,95.3 "/>
<polygon class="st0 regio-2 regio" points="133.3,165.3 129.3,173 116.7,182 112.3,185.3 112.3,192.7 115.7,196.3 118.3,203.7 136,225.3
139.7,227.7 156,227.7 159.7,224 159.7,197.3 169.7,169.3 170.7,151.3 153,165.7 146.7,169.3 "/>
...
</g>
</svg>
This is what I tried:
var svg = Snap('#svgRegioKaart'); Snap.load("path_to_svg", function(f) { var layer0 = f.select('g'); $.each(layer0.selectAll(".regio").items, function() { this.click(function() { debugger; this.attr({ class: 'st1' }); }); }); svg.append(layer0); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/snap.svg/0.4.1/snap.svg-min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <svg id="svgRegioKaart" height="567" width="567"></svg>
I found this tutorial http://www.pixelite.co.nz/article/using-snap-svg-for-rich-interactivity/ but it seems that doesn't work in my case...
You need to 'append' the fragment that you load into the DOM, otherwise you are trying to add a click handler to something not fully in the DOM.
So after this line...
var layer0 = f.select('g');
Add
svg.append(layer0); // or svg.append( f ) and remove prev line if you want all the svg loaded
Then select from the svg you have now appended using Snap...
svg.selectAll(".regio").forEach( function() {
this.click( function() {....} )
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.