How can I alter the color of a circle when a div is clicked on?

When I hover over 4 divs, their background color changes. Now, I want to click on each of them to change the color of a circle inside an SVG tag. Below are my codes:

#a1,
#a2,
#a3,
#a4 {
  display: inline-block;
  position: relative;
  border: 2px solid black;
  width: 100px;
  height: 100px;
}

#a1:hover {
  background-color: orangered;
}

#a2:hover {
  background-color: green;
}

#a3:hover {
  background-color: blue;
}

#a4:hover {
  background-color: yellow;
}

<div style="width:25%; margin:auto; text-align:center;">
  <div id="a1"></div>
  <div id="a2"></div>
  <div id="a3"></div>
  <div id="a4"></div>
</div>

<svg id="b" height="100" width="100">
   <circle cx="50" cy="50" r="40"  />
</svg>

Is it possible to achieve this using only CSS without JavaScript or JQuery?

Answer №1

To achieve this effect, you can use a clever trick involving radio buttons where the circle color is linked to the checked radio button.

#a1:checked~svg circle {
  /*The style specified here will be applied when the radio button with id = a1 is checked.*/
}

Take a look at the code below:

#l1,
#l2,
#l3,
#l4 {
  display: inline-block;
  position: relative;
  border: 2px solid black;
  width: 100px;
  height: 100px;
  display: inline-block;
}

#l1:hover {
  background-color: orangered;
}

#l2:hover {
  background-color: green;
}

#l3:hover {
  background-color: blue;
}

#l4:hover {
  background-color: yellow;
}

.check-btn input {
  display: none;
}

#a1:checked~svg circle {
  fill: orangered;
}

#a2:checked~svg circle {
  fill: green;
}

#a3:checked~svg circle {
  fill: blue;
}

#a4:checked~svg circle {
  fill: yellow;
}
<div class="check-btn">

  <input id="a1" type="radio" name="color">
  <label id="l1" for="a1" class="clicker"></label>
  <input id="a2" type="radio" name="color">
  <label id="l2" for="a2" class="clicker"></label>
  <input id="a3" type="radio" name="color">
  <label id="l3" for="a3" class="clicker"></label>
  <input id="a4" type="radio" name="color">
  <label id="l4" for="a4" class="clicker"></label>

  <svg id="b" height="100" width="100">
    <circle cx="50" cy="50" r="40" />
  </svg>
</div>

Answer №2

Using Pure CSS

(employing the checkbox (or radio button) hack)

[name='c'] {
position: absolute;
right: 100%
}

#black:checked ~ svg circle { fill: black }
#purple:checked ~ svg circle { fill: purple }
#hotpink:checked ~ svg circle { fill: hotpink }
#orange:checked ~ svg circle { fill: orange }
<input type='radio' name='c' id='black' checked/>
<input type='radio' name='c' id='purple'/>
<input type='radio' name='c' id='hotpink'/>
<input type='radio' name='c' id='orange'/>

<div style='width:25%; margin:auto; text-align:center;'>
<div id='a1'><label for='black'>black</div>
<div id='a2'><label for='purple'>purple</div>
<div id='a3'><label for='hotpink'>hotpink</div>
<div id='a4'><label for='orange'>orange</div>
</div>

<svg id='b' height='100' width='100'>
<circle cx='50' cy='50' r='40'  />
</svg>

Keep in mind, opting for a purely CSS solution may not always be the optimal choice.


A Basic JS Approach:

const _C = document.querySelector('circle');

addEventListener('click', e => {
const _T = e.target;

if(_T.id.match(/a[1-4]/)) {
_C.setAttribute('fill', _T.textContent)
}
}, false);
<div style='width:25%; margin:auto; text-align:center;'>
<div id='a1'>black</div>
<div id='a2'>purple</div>
<div id='a3'>hotpink</div>
<div id='a4'>orange</div>
</div>

<svg id='b' height='100' width='100'>
<circle cx='50' cy='50' r='40'  />
</svg>

Answer №3

If you want to change the color dynamically using JavaScript, here is a simple solution:

<div id="colorChoices" style="width:30%; margin:auto; text-align:center;">
        <div class="option" id="choice1"></div>
        <div class="option" id="choice2"></div>
        <div class="option" id="choice3"></div>
        <div class="option" id="choice4"></div>
    </div>

    <svg id="canvas" height="100" width="100">
        <circle cx="50" cy="50" r="40" />
    </svg>

USING JQUERY:

$(document).ready(function(){

  var selectedColor;

  $("#colorChoices .option").click(function(){
    selectedColor = $(this).css("backgroundColor");
    $("#canvas circle").css("fill", selectedColor);
  })

})

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

Distances measured in relation to the present Div

When trying out the jQuery animation effect by editing margins to move, an issue arose. The problem is that while using the animation effect within a div that contains most of the content on the page, the edited margin ends up being relative to the actual ...

Looking to switch up the hide/show toggle animation?

Currently, I have a functioning element with the following code. It involves an object named #obj1 that remains hidden upon page load but becomes visible when #obj2 is clicked. #obj1{ position:fixed; width:100px; bottom:180px; right:10 ...

Insert at the beginning of the element only if the class is 'active'

I'm really struggling with this issue. I am attempting to dynamically add a span element to the link inside a list item when it changes to the 'active' class. Here is my HTML: <ul> <li class="active"> <a href="#when"&g ...

Enhancing jQuery Mobile listview with voting buttons on each item row

I am looking to incorporate 2 vote buttons within a jQuery mobile listview, positioned on the left-hand side and centered within each list item. While I have managed to achieve this using javascript, my goal is to accomplish it without any additional scrip ...

Is it safe to use handlebars' default escaping in HTML attributes?

Currently, I am working on a project where various HTML escaping methods are being utilized. Some properties are escaped in the backend and displayed as raw strings using triple handlebars {{{escaped-in-backend}}}, while others are passed from the backend ...

jquery event delegation doesn't function properly on statically rendered content

When trying to use jQuery event delegation, I encountered an issue where it worked perfectly on elements that were dynamically added but not on static content already present. The 'alert('test')' function performed as expected on the dy ...

The text input is malfunctioning in the IE web browser

For my project, I am incorporating AngularJS but encountering an issue with the input type text in IE browsers specifically IE 11 and IE 10. The problem arises when clicking on the input box - while the focus is triggered, the cursor does not appear insid ...

Troubleshooting issue with AngularJS ng-repeat not functioning properly when using Object key value filter with ng-model

Is there a way to have an object with an ID as a key value pair? For example: friends = { 1:{name:'John', age:25, gender:'boy'}, 2:{name:'Jessie', age:30, gender:'girl'}, 3:{name:'Johanna', ag ...

Using Page.ResolveClientUrl in JavaScript or jQuery allows for easy resolution of client

I find myself in a predicament where I need to choose between using an HTML page instead of a .aspx page for performance reasons. Currently, I am using an aspx page solely because of the CSS and javascript file paths like: <script type="text/javascript ...

Open up the index.html page whenever the page is refreshed

Currently, I am utilizing the fullPage.js plugin to enable page-by-page scrolling. This plugin utilizes hash URLs for navigation. However, upon refreshing the page, it always loads at the last visited hash URL. Is there a way to ensure the document loads a ...

What is the best way to adjust viewport settings for child components, ensuring the container size is set to 100vw/100vh for all children

Within my project, I have connected the react-static repository with the react repository using yarn link. "react": "^16.13.1" "react-static": "^6.0.18" I am importing various components from the react-static reposi ...

Can anyone suggest a method to set up a group chat without the need for a database?

I am interested in setting up a group chat where all messages and corresponding usernames are stored in a JSON file. However, achieving this without the use of node.js or MySQLi seems to be quite challenging. Currently, I am able to read the JSON file an ...

Is there a more concise method to achieve this in JavaScript? (details below)

I am developing a calculator and implementing eventListeners to the number buttons using JavaScript. Here is the code snippet: document.addEventListener('click', e =>{ if (e.target.matches('#num1')){ const x = document.cr ...

Can you use CSS to target a parent div based on the elements it contains?

If I have the following HTML: <div class='row'> <div class='cell'> <span class='image'> </span> Image Cell </div> <div class='cell'> Regular Cell </div&g ...

Setting cards to have the same height in a Vue JS card set

Here is a card component example: <div name="card container" class="flex max-w-[25vw] flex-grow flex-col gap-3 rounded-xl border-2 border-green-600 transition-all duration-500 hover:scale-105" > <div name= ...

I am having trouble displaying an image on a page within my Vuetify project

I've organized my directories in a similar structure as shown here All images are saved in the assets folder. On my HTML page, I'm using this tag: <img :src="imageLink"> where imageLink is a string defined like this: imageLink ...

Encountering difficulties loading Google Maps with jQuery

When attempting to load a map on my page, I encountered a problem when including the jquery.min.js file in the head tag. If it is included, I receive an initMap : no such method error. However, if I reverse the order of inclusion, with maps first and then ...

When using JavaScript to style.display = "block", the Bootstrap-4 column layout may experience a display break

My div is initially displaying properly in one row at the beginning. However, when the user changes the select option to "b" and then back to "a," the display breaks. The two texts "my left side text" and "my right text" are displayed on two lines, one be ...

Map / Area enveloped in darkness

I'm currently working on a map that includes an area, but I'd like to add a shadow effect around it. I'm struggling to figure out how to achieve this. <map name="map_bottom"> <area id="area_bottom" shape="poly" coords="0,0,0,37 ...

Is it possible to assign ng-model to multiple values simultaneously?

I am currently working on incorporating an input field into my project. <input type="text" ng-model="choice.text"> Using choice.text allows me to create a new text property within the object choice. This functionality enables me to send the input c ...