1

I'm making a pixel art maker, and I want to have a color palette that users can get colors from. I have an event that listens for users clicking a div in the color palette, but when I try to access the background color of the div, it just gives me plain white.

function listenColors() {
    let colors = document.querySelectorAll('.colors');
    colors.forEach((member) => {
        member.addEventListener('click', function() {
            color = member.style.backgroundColor;
        });
    });
}

Does .style.backgroundColor not access the actual background color?

https://jsfiddle.net/wgra9dqj/1/

JusticeDunn
  • 115
  • 9
  • 1
    The colors are assigned via CSS classes, so you need [getComputedStyle](https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle) –  Sep 21 '20 at 23:26
  • https://stackoverflow.com/questions/12576084/getting-the-real-background-color-of-an-element – epascarello Sep 21 '20 at 23:38
  • `window.onload = createGrid(25, 25); window.onload = createPalette();` That is wrong. Only reason it works is you did it wrong. – epascarello Sep 21 '20 at 23:58

2 Answers2

2

You want to get the computed style for this. Something like the following:

HTML
<div id="foo"></div>
CSS
.foo {
  width: 100px;
  height: 100px;
  background: lightgreen;
}
JS
const foo = document.getElementById('foo');

console.log(window.getComputedStyle(foo).getPropertyValue('background-color'));

//  outputs: 'rgb(144, 238, 144)'
Richard Hunter
  • 1,933
  • 2
  • 15
  • 22
1

You need to look at the Computed Style

function listenColors() {
    let colors = document.querySelectorAll('.colors');
    colors.forEach((member) => {
        member.addEventListener('click', function() {
            color = window.getComputedStyle(member, null).getPropertyValue("background-color");
        });
    });
}

You also have a bug with onload. You can not use window.onload more than once. The second one will override the first. Only reason why it works is you are executing the function and assigning what it returns to the event listener.

window.addEventListener("load", function () {
  createGrid(25, 25);
  createPalette();
});
epascarello
  • 204,599
  • 20
  • 195
  • 236