0

How to change color of svg circle genereted by for loop.

Im trying to change color of circle by right click and then save it into array.

var svgInfo = 'http://www.w3.org/2000/svg';
var customSvg = document.querySelector('svg');

var points = [
    {x: 5, y: 5},
    {x: 50, y: 50},
];

var selected = [];
for (var i = 0; i < points.length; ++i) {
    var circle = document.createElementNS(svgInfo, 'circle');
    circle.setAttribute('cx', points[i]["x"]);
    circle.setAttribute('cy', points[i]["y"]);
    circle.setAttribute('stroke', 'red');
    circle.setAttribute('stroke-width', 5);
    circle.setAttribute('r', 5);
    circle.setAttribute('fill', 'green');
    circle.setAttribute('fill-opacity', 0);
    circle.setAttribute('id', points[i]["id"]);
    circle.addEventListener('contextmenu', function (event) {
        let s = 0;
        circle.setAttribute('stroke', 'green');
        selected[s] = {id: circle.id, x: circle.cx, y: circle.cy};
        s++;
        event.preventDefault();
    });
    customSvg.appendChild(circle);
}
<svg></svg>
str
  • 42,689
  • 17
  • 109
  • 127
Patrik
  • 41
  • 1
  • 1
  • 5
  • Please post a working example after reading: [How to create a Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example) – Randy Casburn Jun 18 '19 at 19:06
  • Possible duplicate of [addEventListener using for loop and passing values](https://stackoverflow.com/questions/19586137/addeventlistener-using-for-loop-and-passing-values) and [JavaScript closure inside loops – simple practical example](https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – str Jun 18 '19 at 19:09

1 Answers1

0

In order to make it work I've added an id to every point since you have this line of code: circle.setAttribute('id', points[i]["id"]);

Also I've replaced var circle with let circle

var svgInfo = 'http://www.w3.org/2000/svg';
var customSvg = document.querySelector('svg');

var points = [
    {x: 5, y: 5,id:"a"},
    {x: 50, y: 50,id:"b"},
];

var selected = [];
for (var i = 0; i < points.length; i++) {
    let circle = document.createElementNS(svgInfo, 'circle');
    circle.setAttribute('cx', points[i]["x"]);
    circle.setAttribute('cy', points[i]["y"]);
    circle.setAttribute('stroke', 'red');
    circle.setAttribute('stroke-width', 5);
    circle.setAttribute('r', 5);
    circle.setAttribute('fill', 'green');
    circle.setAttribute('fill-opacity', 0);
    circle.setAttribute('id', points[i]["id"]);
    circle.addEventListener('contextmenu', function (event) {console.log(circle.id)
        let s = 0;
        circle.setAttribute('stroke', 'green');
        selected[s] = {id: circle.id, x: circle.cx, y: circle.cy};
        s++;
        event.preventDefault();
    });
    customSvg.appendChild(circle);
}
svg {
  border: 1px solid;
}
<svg></svg>
enxaneta
  • 31,608
  • 5
  • 29
  • 42