skip to Main Content

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?

3

Answers


  1. 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

    Login or Signup to reply.
  2. 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>
    Login or Signup to reply.
  3. 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;
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search