samedi 21 août 2021

Detecting change in css backgroundColor using Vanilla JavaScript

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.

Aucun commentaire:

Enregistrer un commentaire