If you're open to making this adjustment in your design, your existing css code will still function correctly:
One notable change I made was relocating the closing tag for
<div id="circ-toggle" class="toggle">
to the end of your css, ensuring that it surrounds
<div id="circles">
. By doing so, a sibling relationship is established between the
checkbox
and
<div id="circles">
. This modification enables the
general sibling combinator (~) to target the desired element effectively.
If needed, javascript could easily achieve the same outcome, but it seems you prefer a css-only solution.
const checkbox = document.getElementById('toggle-1')
checkbox.addEventListener('change', (event) => {
if (event.currentTarget.checked) {
alert('checked');
} else {
alert('not checked');
}
})
#circles {
fill: #00ffff;
}
.gray {
fill: #000000;
fill-opacity: 0.3;
}
<div id="circ-toggle" class="toggle">
<input type="checkbox" id="toggle-1" class="toggler">
<label for="toggle-1" class="btn-toggle">Change Color</label>
</div>
<div id="circles">
<svg viewBox="0 0 40 30">
<g>
<circle class="circ1" cx="1" cy="1" r="1" />
<circle class="circ2" cx="3" cy="1" r="1" />
</g>
</svg>
</div>
EDIT: Below is a javascript approach:
const checkbox = document.getElementById('toggle-1');
const circle = document.querySelector("#circles > svg > g > circle.circ1");
checkbox.addEventListener('change', (event) => {
if (event.currentTarget.checked) {
circle.classList.add("gray");
} else {
circle.classList.remove("gray");
}
})
#circles {
fill: #00ffff;
}
.gray {
fill: #000000;
fill-opacity: 0.3;
}
<div id="circ-toggle" class="toggle">
<input type="checkbox" id="toggle-1" class="toggler">
<label for="toggle-1" class="btn-toggle">Change Color</label>
</div>
<div id="circles">
<svg viewBox="0 0 40 30">
<g>
<circle class="circ1" cx="1" cy="1" r="1" />
<circle class="circ2" cx="3" cy="1" r="1" />
</g>
</svg>
</div>