I have created a series of SVG circles that are meant to alternate in color between blue and red with each click. However, I am experiencing some inconsistency in the behavior. In my local environment, the color doesn't change to red until the second click. When I tried running the code in jsFiddle, one circle works while the other does not, even though the code is identical, and both throw the same error in the console.
[Error] ReferenceError: Can't find variable: changeColor1 onclick (_display:79)
var shapeClick = document.getElementById("circle0").addEventListener("click", changeColor);
var clicks = 0;
var colorToggle = true;
function changeColor() {
var color = colorToggle ? "#ff0000" : "#1dacf9";
circle0.setAttribute('fill', color);
colorToggle = !colorToggle;
}
var shapeClick = document.getElementById("circle1").addEventListener("click", changeColor1);
var clicks = 0;
var colorToggle = true;
function changeColor1() {
var color = colorToggle ? "#ff0000" : "#1dacf9";
circle1.setAttribute('fill', color);
colorToggle = !colorToggle;
}
<svg id="table1" width="66%" height="100vh" viewBox="0 0 700 666">
<circle id="circle0" class="circles" cx="170" cy="125" r="20" fill="#1dacf9" stroke="black" stroke-width="2" onclick="changeColor()"/>
<circle id="circle1" class="circles" cx="250" cy="45" r="20" fill="#1dacf9" stroke="black" stroke-width="2" onclick="changeColor1()"/>
</svg>
There must be a more efficient way to achieve this functionality, especially if scaling it up to include 100 circles. It seems challenging without resorting to a significant amount of code.