0

Currently when I select class '.light' javascript knows that my backgroundColor is grey and changes it to blue. But for some reason backgroundColor == "rgb(128, 128, 128)" remains true even after successfully changing to blue, when it needs to turn back to grey. I'm looking for the simplest way to do this in vanilla JavaScript.

let allLights = document.querySelectorAll('.light')

allLights.forEach(light=>{
  
  getComputedStyle(light).backgroundColor === "rgb(128, 128, 128)"
  ? light.addEventListener("click", () => light.style.backgroundColor='blue')
  : light.addEventListener("click", () => light.style.backgroundColor='grey')
});
              

I can do this so easily in jQuery with:

function prepareLights() {
    $('.light').on( 'click', function() {
    $(this).css('background-color') == 'rgb(128, 128, 128)'?
    $(this).css('background', 'blue ') :
    $(this).css('background', 'grey')
  });
};

Thanks in advance for any suggestions or corrections.

Johnny Bravo
  • 163
  • 11
  • 2
    `backgroundColor == "rgb(128, 128, 128)"` doesn’t remain true. You check for it once, bind the listener once, then never check again; in your jQuery code you check for the color _inside_ the listener. Why not simply add a CSS class and check for its existence instead? – Sebastian Simon Aug 22 '21 at 00:39
  • Thanks, Your right, it doesn't remain true, but it still acts like it is because the 2nd piece of logic never Initiates on a 2nd click. You mentioned only checking once and binding once, which confused me. Im still kinda figuring out the whole binding thing. My intention is for my if statement to check if it's true each time I click on the element – Johnny Bravo Aug 22 '21 at 04:07

1 Answers1

0

I figured something out that works a little better. Now the only issue is the logic can't detect that my backgroundColor is already grey from the css style sheet on the first click, so it only changes color on the 2nd click after it added grey to the element.style on first click.

var allLights = document.querySelectorAll(".light");

allLights.forEach(light=>{
  light.addEventListener("click", function() {
  const curColour = light.style.backgroundColor;
  light.style.backgroundColor = curColour === 'grey' ? 'blue' : 'grey';
})
})
Johnny Bravo
  • 163
  • 11