Home > database >  How do I make the circle div in the center change color from yellow to white and vice versa on every
How do I make the circle div in the center change color from yellow to white and vice versa on every

Time:10-12

So far I have managed to do this on single click.

I removed the lightbulb image

const div = document.getElementById("sphere");

div.addEventListener("click", e => {
    console.log("You clicked the mouse!");
    div.style.backgroundColor = "white";
})

How do I make the circle div in the center change color from yellow to white and vice versa on every click inside the circle?

CodePudding user response:

You can just try this way:

 const div = document.getElementById("sphere");

      div.addEventListener("click", e => {
        console.log("You clicked the mouse!");
        div.classList.toggle('active')
      })
#sphere {
        width: 100px;
        height: 100px;
        border-radius: 50%;
        background-color: yellow;
      }

      img {
        width: 50px;
        height: 50px;
        display: block;
        margin-left: auto;
        margin-right: auto;
        padding-top: 20px;
      }

      #sphere.active {
        background-color: white;
      }
<div id="sphere">
      <img src="https://freepngimg.com/thumb/bulb/31669-1-bulb-off-transparent-image.png">
    </div>

CodePudding user response:

I would create one css class white (background white) and one yellow (background yellow). Then with js you just add or remove the class you want.

Or you can make it white by default and just create a yellow background class, then you use js toggle class which add or remove automatically a class https://www.w3schools.com/howto/howto_js_toggle_class.asp

Hope it helps

CodePudding user response:

To do this without toggling classes you can create a variable to keep track of which color is being displayed. Something like this:

const div = document.getElementById("sphere");
let isWhite = false;

div.addEventListener("click", e => {
    console.log("You clicked the mouse!");
    div.style.backgroundColor = isWhite ? "white" : "yellow";
    isWhite = !isWhite;
})
  • Related