2

I have an svg path with the following points in the 'd' attribute. This there a way for me to target just one of the coordinate numbers in 'd' say like 0 in "L25 0 " to manipulate in java script. IF so what would this syntax look like? I am hoping to have access to one of the coordinate number so that I can increment it to animate the path.

function NavHalf() {
  var arrow = document.getElementById("arrowUp");
  arrow.setAttribute('d', 'M0 25 L25 0 L50 25');
}
<svg height="25" width="50" onclick="NavHalf()">
   <path id="arrowUp" d="M0 0 L25 25 L50 0 " style="stroke:green;stroke-width:2; fill:none" />
</svg>
georg
  • 211,518
  • 52
  • 313
  • 390
Nhan Bui
  • 157
  • 1
  • 1
  • 9
  • SVG 1.1 had a DOM interface - PathSegList that you could use to index into individual path elements - but I think this was removed in Chrome and is deprecated in general. – Michael Mullany Oct 19 '19 at 00:53
  • [This](https://stackoverflow.com/questions/6813931/change-svg-path-with-javascript) question looks similar to yours, and the top two answers seem like they contain the info you need. – Alexander Nied Oct 19 '19 at 01:47
  • You could use an array to hold your coordinates (`["M0 25", "L25 25" ,... ]`) to make it easier to manage and then use `.join()`to parse it back to a string – Dom Oct 19 '19 at 06:02
  • Please use [setAttributeNS](https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttributeNS) instead of `setAttribute` – enxaneta Oct 19 '19 at 07:33
  • 1
    @enxaneta There is no need to use setAttributeNS() here. – Paul LeBeau Oct 20 '19 at 09:13
  • @NhanBui You can accept one answer (if it helps you) by click on big gray check button on its left side. If you wish you can add +10 points to any author of any good answer by click upper gray triangle – Kamil Kiełczewski Nov 30 '19 at 13:10

1 Answers1

3

As Michaels commented. There isn't really any DOM-based way to directly access and manipulate just one of the points in a path definition.

String manipulation is about all you can do.

function NavHalf(x,y) {
  var arrow = document.getElementById("arrowUp");
  arrow.setAttribute('d', 'M0 0 L' + x + ',' + y + ' L50 0');
}
<button type="button" onclick="NavHalf(25,0)">Position 1</button>
<button type="button" onclick="NavHalf(20,15)">Position 2</button>
<button type="button" onclick="NavHalf(25,25)">Position 3</button>

<svg height="25" width="50">
   <path id="arrowUp" d="M0 0 L25 25 L50 0" style="stroke:green;stroke-width:2; fill:none" />
</svg>
Paul LeBeau
  • 97,474
  • 9
  • 154
  • 181