How can I get the X and Y coordinates of a path in jQuery and then change them? I wanting to be able to animate my icon on click. I know there are other ways but would like to use jQuery
<svg class="path" style="height: 32px; width: 32px;">
  <g style="stroke: #ff6633; stroke-width: 4px;" fill="none" stroke-linecap="round">
    <path d="M2 4 L30 4" />
    <path d="M2 16 L30 16" />
    <path d="M2 28 L30 28" />
  </g>
</svg>Change the path attribute to newPath using .attr("d", newPath); with JQuery.
Here's and example where each single path has a click event attached to it.
You can use any string manipulation method for changing the attribute d in the path.
// click event on a path element of the SVG
$('path').click(function() {
  var path = $(this).attr("d");
  // just as an example, substitute the first two characters in d ("M2") with "M20"
  path = "M20" + path.slice(2); // here you manipulate the path as a string
  console.log(path); // check new path in the console
  $(this).attr("d", path);
});<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<svg class="path" style="height: 32px; width: 32px;">
  <g style="stroke: #ff6633; stroke-width: 4px;" fill="none" stroke-linecap="round">
    <path d="M2 4 L30 4" />
    <path d="M2 16 L30 16" />
    <path d="M2 28 L30 28" />
  </g>
</svg>This example shows you how to make the svg clickable and select all children paths in the svg. If you want to select a specific path, you can add an id to it.
// select the svg element
$('svg').click(function() {
  $(this).find("path").each(function(index) {
    var d = $(this).attr("d");
    d = "M" + 10 * index + d.slice(2); // manipulate path 
    $(this).attr("d", d);
  })
});<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<svg class="path" style="height: 32px; width: 32px;">
  <g style="stroke: #ff6633; stroke-width: 4px;" fill="none" stroke-linecap="round">
    <path d="M2 4 L30 4" />
    <path d="M2 16 L30 16" />
    <path d="M2 28 L30 28" />
  </g>
</svg>If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With