Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

toggle svg circle color with checkbox

I would like a toggle button that changes the color of a svg, a circle in this case. I am able make a checkbox that changes the color of text purely in HTML and CSS, but it is not working with an svg.

Here is the code that works for text.

<label for="element-toggle">click me to toggle color</label>
<input id="element-toggle" type="checkbox" />

<div id="toggled-element">My color will be toggled</div>
label[for=element-toggle] {
  cursor: pointer;
  color: blue;
}

#toggled-element {
  color: green;
}

#element-toggle:checked ~ #toggled-element {
  color: red;
}

Here is my attempt to use the same logic to change the color of an svg circle instead of text (this doesn’t work)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<label for="element-toggle">click me to toggle color</label>
<input id="element-toggle" type="checkbox" />

<svg viewBox="0 0 40 30">
  <circle id="toggled-element" cx="1" cy="1.2" r="1" />
</svg>
label[for=element-toggle] {
  cursor: pointer;
  color: blue;
}

#toggled-element {
  fill: green;
}

#element-toggle:checked ~ #toggled-element {
  fill: red;
}

>Solution :

The wrong element was being targeted…

I switched the id="toggled-element" to the svg as opposed to the circle to demonstrate.

This #element-toggle:checked~#toggled-element actually selects the svg by way of the general sibling combinator.

label[for=element-toggle] {
  cursor: pointer;
  color: blue;
}

#toggled-element {
  fill: green;
}

#element-toggle:checked~#toggled-element {
  fill: red;
}
<label for="element-toggle">click me to toggle color</label>
<input id="element-toggle" type="checkbox" />

<svg viewBox="0 0 40 30" id="toggled-element">
  <circle cx="1" cy="1.2" r="1" />
</svg>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading