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
Elements in HTML must have a unique id
attribute, otherwise, your HTML is considered invalid.
Instead, you should use a class
, this way you can iterate through your selected elements (here I have used .forEach
), and apply the click
handler to each.
Note: Now that you're using a class, you need to use getElementsByClassName()
which will give you a HTMLCollection of matching elements.
See working example below:
const circles = [...document.getElementsByClassName("circle1")], // use spread syntax to convert collection to array
colors = ['orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];
circles.forEach(circle => {
circle.onclick = function() {
color = colors.shift();
colors.push(color);
circle.style.fill = color;
}
});
Rainbow Colours