I am new to javascript and I have an assignment to create seven circles which should change colour on a mouse click. The first circle is changing colour but the other six just r
In the onclick function pass the element itself using this keyword. It works in this case but remember it is wrong to give same id to more than 1 element. It should be unique.
var circle = document.getElementById("circle1");
colors = ['orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];
function a(e)
{
color = colors.shift();
colors.push(color);
e.style.fill = color;
}
<html>
<body>
<h2> Rainbow Colours</h2>
<svg height="1000" width="500">
<circle id="circle1" onclick="a(this)" cx="50" cy="50" r="40"
style="fill:red;"/>
<circle id ="circle1" onclick="a(this)" cx="50" cy="150" r="40"
style="fill:red;"/>
<circle id ="circle1" onclick="a(this)" cx="50" cy="250" r="40"
style="fill:red;"/>
<circle id ="circle1" onclick="a(this)" cx="50" cy="350" r="40"
style="fill:red;"/>
<circle id ="circle1" onclick="a(this)" cx="50" cy="450" r="40"
style="fill:red;"/>
<circle id ="circle1" onclick="a(this)" cx="50" cy="550" r="40"
style="fill:red;"/>
<circle id ="circle1" onclick="a(this)" cx="50" cy="650" r="40"
style="fill:red;"/>
</svg>
</body>
</html>
You have multiple element with same id. Instead of id use class and add event listener to it
var circle = document.getElementsByClassName("circle");
let colors = ['orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];
[...circle].forEach(function(item, index) {
item.addEventListener('click', function(e) {
item.style.fill = colors[index]
})
})
<h2> Rainbow Colours</h2>
<svg height="1000" width="500">
<circle id="circle1" class ="circle" cx="50" cy="50" r="40"
style="fill:red;"/>
<circle id ="circle1" class ="circle"cx="50" cy="150" r="40"
style="fill:red;"/>
<circle id ="circle1" class ="circle" cx="50" cy="250" r="40"
style="fill:red;"/>
<circle id ="circle1" class ="circle" cx="50" cy="350" r="40"
style="fill:red;"/>
<circle id ="circle1" class ="circle" cx="50" cy="450" r="40"
style="fill:red;"/>
<circle id ="circle1" class ="circle" cx="50" cy="550" r="40"
style="fill:red;"/>
<circle id ="circle1" class ="circle" cx="50" cy="650" r="40"
style="fill:red;"/>
</svg>