0

I have an event listener which listens for a click on an element, and then runs a function that checks if the background colour of the element is white. Here is my code:

setting.addEventListener("click", (e) => {
       if (e.target.style.backgroundColor == "white") {
           e.target.style.backgroundColor = "black";
       } else {
           console.log(e.target.style.backgroundColor);
           e.target.style.backgroundColor = "white";
       }
});

My intention is that the element will first turn black, since its background colour is white.

Here is my css for this element:

.toggle {
    display: inline-block;
    height: 20px;
    width: 20px;
    background-color: white;
    border-radius: 50%;
    position: absolute;
    right: 300px;
    outline: 3px solid black;
    border: 3px solid white;
}

The console log in the js logs this message:

<empty string>

Why is this happening, and how should I fix it?

  • 3
    because the `style` attribute only returns inline styles, not styles applied through external style sheets. After the first click you will have set an inline style and it will work going forward. Also see: [Window.getComputedStyle()](https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle) – pilchard Jul 02 '22 at 21:29
  • You should add [minimal reproducible code](https://stackoverflow.com/help/minimal-reproducible-example), so that people can understand your problem clearly. – DecPK Jul 02 '22 at 21:30
  • and [JS does not enter the first block at first click](https://stackoverflow.com/questions/64188881/js-does-not-enter-the-first-block-at-first-click) – pilchard Jul 02 '22 at 21:32
  • Another problem you will encounter is that `white` is not equal to `White`, and neither equal to `#fff`, `#ffffff`, `rgb(255,255,255)` or `hsl(0,0%,100%)`. To name a few... – Rene van der Lende Jul 02 '22 at 22:10

0 Answers0