Matt
Matt

Reputation: 133

Get id of clicked svg path with javascript

I have an SVG map of counties in Massachusetts. The svg file contains paths outlining each county, and each path has the name of the county as its id. I need to grab the id of the county when it is clicked, so that it can be set to a variable.

Edit: The SVG is an external file (it's a map with a ton of path coordinates; it seems like it would be messy to copy/paste the whole thing directly into the HTML, so it's being loaded from the external file). Here is a sample of the svg file:

<?xml version="1.0" encoding="iso-8859-1"?>
<?xml-stylesheet type="text/css" href="co25_d00.css"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20000303 Stylable//EN"
    "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">

<svg id="MACounties"
   xmlns:svg="http://www.w3.org/2000/svg"
   xmlns="http://www.w3.org/2000/svg"
   xmlns:xlink="http://www.w3.org/1999/xlink"
   version="1.0" width="100%" height="100%" preserveAspectRatio="xMidYMax" viewBox="12.711167 456.567074 29.566845 18.433033">
<title>Libre Map Project</title>
<g transform="scale(1.0,-1.0) translate(0,-931.567181)">
<g id="Unknown_Area_Type_co25_d00_e00" style="fill:'currentColor';pointer-events:visible;stroke:rgb(1,0,0);stroke-width:0.01;stroke-linecap:round">
    <path id="Essex" d="M34.363079 474.99995L34.363179 474.99967 34.363179 474.99967 34.462128 474.99704 34.596972 474.95046...>

Edit 2: This is the HTML file where the image is being loaded.

<html>
<head>
    <title>Untitled</title>
    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="co25_d00.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script type="text/javascript">
        $(function(){

              var container = $("#map");
              var svgUrl    = "co25_d00.svg";
              var xmlDoc;

              $.get(svgUrl)
                .then(injectSvg);

              function injectSvg(xmlDoc) {
                var svg = $(xmlDoc).find("svg");
                container.append(svg);
              };

              $(document).ready(function() {
                $('path').onclick = function() {
                    alert($(this).attr('id'));
                };
              });
            });
    </script>
</head>
<body>
    <div id="map"></div>
</body>
</html>

Upvotes: 3

Views: 3503

Answers (1)

Ecropolis
Ecropolis

Reputation: 2025

Your event binding needs to be inside of your callback. Like

  $.get(svgUrl)
      .done(function( svgdata ) {
          injectSvg(svgdata);
          $('path').on('click', function() {
              alert($(this).attr('id'));
          });
  });

Upvotes: 3

Related Questions