Home > Software engineering >  Call back a function to change the div color after click on button click on div
Call back a function to change the div color after click on button click on div

Time:06-24

hello everyone. I'm strugling to do some piece of code with 2 different buttons colors that when clicked, they change the color value so when I click the div it changes to that color. I found that I can do it the first time but I can not call again the function to repeat the process all over again. Any suggestions? Thank you a lot :)

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <style>
.green {
  background-color: green;
}

.red {
  background-color: red;
}

#change {
  border: 1px solid black;
  width: 500px;
  height: 500px;
}
 
 </style>
  </head>
  <body>
<div id="change"></div>
<button id="green-btn">Green</button>
<button id="red-btn">Red</button>
 
    <script>

  const gbutton = document.getElementById("green-btn");
  const rbutton = document.getElementById("red-btn");
  const change = document.getElementById("change");
  let color = "";
  
  
  function changeGreen () {
    color = "green";
  }
 
  
  function changeRed () {
    color = "red";
  }
 
  gbutton.addEventListener("click", changeGreen)
  rbutton.addEventListener("click", changeRed)

  change.addEventListener("click", () => { 
   
    if(color == "green") {
      change.classList.add("green");
    } else if (color == "red") {
      change.classList.add("red");
    }});


   </script>
  </body>
</html>

CodePudding user response:

you just have to remove other class

change.addEventListener("click", () => {
  console.log('color', color)
  if (color == "green") {
    change.classList.add("green");
    change.classList.remove("red");
  } else if (color == "red") {
    change.classList.add("red");
    change.classList.remove("green");
  }
});

CodePudding user response:

you should remove the other class

change.classList.add("green")
change.classList.remove("red")
  • Related