JavaScript – Background switch between green and white with button

I wanted to ask how I do it, when you click the button, the background turns green, it goes back again with the same button, so that it then becomes white again.

spanTwo.addEventListener('click', () =>{
      liItem.style.background = 'rgb(24, 189,24';
      liItem.style.color = 'white';
     

Answer

  • There’s too many ways to do that you can try one of those
  1. Check the element background and apply your style
spanTwo.addEventListener('click', () =>{
      if(getComputedStyle(liItem, null).backgroundColor !== "rgb(24, 189, 24)") {
           liItem.style.backgroundColor = 'rgb(24, 189, 24)';
           liItem.style.color = 'white';
      } else {
           liItem.style.backgroundColor = 'rgb(0, 0, 0)';
           liItem.style.color = 'white';
      }
})
  1. Toggle class
.liItem {
    background: #000;
    color: #fff;
}
.green {
    background: rgb(24, 189, 24);
    color: #fff;
}
spanTwo.addEventListener('click', () =>{
      liItem.classList.toggle("green")
})