Modifying the color of an SVG shape with a checkbox toggle

Is there a way to dynamically change the fill color of an SVG shape by clicking on a checkbox? I have managed to achieve this functionality, but when I enclose the checkbox input in a div tag, it stops working.

#circles {
  fill: #00ffff;
}

#circ-toggle .toggler:checked~#circles .circ1 {
  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>

Answer №1

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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Identifying all elements with querySelectorAll and monitoring events with

I am currently attempting to modify this demonstration for page transitions triggered by clicking on links with a shared class. Despite following @ourmaninamsterdam's suggestion here, I am facing difficulties in getting the transitions to work. Can yo ...

The gulp-sass import feature has been acting up quietly

I'm currently attempting to transpile a scss file using gulp-scss. However, when I execute the task, it seems that the imports are not being recognized. gulpfile.js gulp.src('./app/css/app.scss', {base: './'}) .pipe(sass({inc ...

What is the best method for uploading photos via ajax in a django application?

Currently, I am in the process of creating a function that allows users to update their profiles by changing their email addresses, names, and profile pictures. While I have been successful in updating emails and names, I have encountered difficulties in u ...

Hide or show list items in an unordered list using jQuery

I am interested in creating a script that can toggle between "show more" and "show less" functionality for elements in a list. I came across this script: HTML <ul id="myList"> <li>One</li> <li>Two</li> <li> ...

Guide to creating HTML file with SSI tags

Currently, my website uses Nginx SSI tags to dynamically include template files such as the header, footer, and sidebar. However, I need to provide the final HTML output to clients instead of running it on their browsers. The issue I'm facing is that ...

I'm searching for a universal guidebook on creating web page layouts

After 5 years of creating webpages, I have realized that my sites tend to have a nostalgic 1995 internet vibe. Despite being a C# programmer with knowledge in HTML, JavaScript, and CSS, my design skills could use some improvement. Is there a quick referenc ...

Translate3d increases the whitespace towards the end of the page

After implementing a smooth scroll on my webpage using transform translate3d, I encountered an issue. The translate3d function seems to be adding extra space at the end of the document, as illustrated here: https://codepen.io/anon/pen/WEpLGE I suspect the ...

I plan to add new information to my table only when the user clicks on the submit button. This is what I have accomplished until now

<!DOCTYPE html> <html> <head> <title>Sign up page</title> </head> <body> <form method="get" action="signup_redirect.php"> username: <input type="text" name="username" placeholder=" ...

The border bottom effect in Hover.css is malfunctioning when used in the Opera browser

I've implemented a hover effect using hover.css that works perfectly in all browsers except Opera. Surprisingly, the effect only seems to work in Opera when I remove the following properties: -webkit-transform: perspective(1px) translateZ(0); transf ...

Using the Ruby on Rails redirect_to method

Imagine I have the following line in my controller: redirect_to "/sessions/attempt", provider: 5 Now, this is what my attempt.html.erb looks like: <h1>attempt</h1> <%= provider %> It's clear that this setup isn't functioning ...

Issue in Chrome where hover state does not persist after clicking, occurring sporadically

It's surprising that I couldn't find any information about this on Google. This bug is really annoying, and I'm not sure if it can be fixed without an update from Google for their browser. Description of the issue: When clicking on an eleme ...

What are the methods for setting the width and height of an Angular mat dialog box?

I'm currently working with a Mat dialog box in Angular and I'm trying to include styles for width and height within that object. However, I'm encountering errors and can't seem to resolve them. Is there another method for setting width ...

What could be causing justify-content: flex-start; to not function as expected?

Can someone help me with my flexbox navbar? I set the justify-content property to flex-start, but the content inside the container is not aligning correctly. You can see the output and code here: output html, body { backgr ...

Setting up the Bootstrap grid structure

Struggling to find the right configuration for this Bootstrap 3 setup... https://i.stack.imgur.com/ZsTdI.png I have an input field, but I'm having trouble placing the image in that position. <div class="row"> <div class="col-sm-4 col-m ...

JQuery is facing difficulty in animating a div following the completion of a "forwards" css animation

Check out this example: http://jsfiddle.net/nxsv5dgw/ A div appears on the stage and a CSS animation is applied to it. However, when attempting to use JQuery to animate the same properties that were animated by CSS, it seems to no longer work properly. ...

Issue with ngRepeat directive

I'm attempting to display an array in a table Below is the relevant code snippet js: var d = [[ '12:00', 'X-Files', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis non nisi in velit tristique scelerisque. ...

How can I create a clickable <div> element containing multiple links and trigger only one action?

Within my code, there is a <div> element that has been made clickable. Upon clicking this <div>, the height and text expand using the jQuery function $(div).animate();. While this functionality works as intended, I am encountering a slight issu ...

In Angular, when a component is clicked, it is selecting entire arrays instead of just a single item at a

I am currently working on implementing a rating feature using Angular. This component will be used to rate different languages based on how proficient I am with them. My issue lies in the fact that when I click on one array element, it automatically selec ...

Dimensions of Bootstrap carousel

I am attempting to create a Bootstrap carousel with full-width images (width: 100%) and a fixed height. However, when I set the width to 100%, the height automatically takes on the same value. I am unsure if the issue lies within my files. <div id="m ...

What steps should I take to prevent my <mat-card> from expanding whenever messages are shown in Angular 9?

I have a <mat-card> containing a login form on my page. However, when error messages are displayed, the vertical size of the <mat-card> changes and I need it to remain the same. Is there a way to prevent this from happening? Below, you will ...