I have the following code in a tiny web page:
<svg width='200' height='200'>
<svg x=0 y=0>
<circle cx=50 cy=50 r=40 stroke='#808080' stroke-width=3 fill='#FF0000'/>
<circle cx=150 cy=50 r=40 stroke='#808080' stroke-width=3 fill='#00FF00'/>
<circle cx=50 cy=150 r=40 stroke='#808080' stroke-width=3 fill='#0000FF'/>
<circle cx=150 cy=150 r=40 stroke='#808080' stroke-width=3 fill='#FFFF00'/>
</svg>
<svg id='CtrBtn' x=0 y=0>
<circle cx=100 cy=100 r=20 stroke='#808080' stroke-width=3 fill='#000000'/>
</svg>
</svg>
<div id='status'>STATUS</div>
<script type='text/javascript'>
window.onload = btnHandler
function btnHandler() {
let divCtrBtn = document.getElementById('CtrBtn')
divCtrBtn.onclick = function() {
document.getElementById('status').innerHTML = 'Center-Button-Hit'
}
}
</script>
It works as I expect showing this for start:
And then this once I click the black button in the middle:
But this is what I want instead when clicking the button:
The red disk should change color to become cyan (#00FFFF) and the green should change color to become magenta (#FF00FF).
How should I change the code of the function btnHandler() to get this result ?
>Solution :
You need to target the fill attribute. In vanilla JS this is done with the setAttribute method.
EDIT:
You also need a way to target them, I’ve just given an id to each circle…
Just add those two extra lines in (see snippet below)
window.onload = btnHandler
function btnHandler() {
let divCtrBtn = document.getElementById('CtrBtn')
divCtrBtn.onclick = function() {
document.getElementById('status').innerHTML = 'Center-Button-Hit'
// extra lines here
document.getElementById('circle1').setAttribute('fill', '#00FFFF')
document.getElementById('circle2').setAttribute('fill', '#FF00FF')
}
}
<svg width='200' height='200'>
<svg x=0 y=0>
<circle id="circle1" cx=50 cy=50 r=40 stroke='#808080' stroke-width=3 fill='#FF0000'/>
<circle id="circle2" cx=150 cy=50 r=40 stroke='#808080' stroke-width=3 fill='#00FF00'/>
<circle id="circle3" cx=50 cy=150 r=40 stroke='#808080' stroke-width=3 fill='#0000FF'/>
<circle id="circle4" cx=150 cy=150 r=40 stroke='#808080' stroke-width=3 fill='#FFFF00'/>
</svg>
<svg id='CtrBtn' x=0 y=0>
<circle id="centreCirle"cx=100 cy=100 r=20 stroke='#808080' stroke-width=3 fill='#000000'/>
</svg>
</svg>
<div id='status'>STATUS</div>

