How do I make a color picker default to a CSS variable?

122 Views Asked by At

I am coding a color picker. I am trying to figure out how to make it default to a CSS variable, and then have it change the CSS variable in question. The variable is called --bg and is for changing the background color.

I tried using value="var(--bg)" but that didn't work. I then tried this JavaScript code generated by ChatGPT:

document.addEventListener('DOMContentLoaded', function() {
    const colorPicker = document.getElementById('bgcolor');
    colorPicker.value = getComputedStyle(document.documentElement).getPropertyValue('--bg').trim();

    colorPicker.addEventListener('input', function() {
        document.documentElement.style.setProperty('--bg', this.value);
    });
});

Still nothing.

1

There are 1 best solutions below

0
Xanoor1 On

you can change the bg color without using a variable:

document.addEventListener('DOMContentLoaded', function() {
    const colorPicker = document.getElementById('bgcolor');

    colorPicker.oninput = function() {
        document.body.style.backgroundColor = colorPicker.value;
    };
});

I have modified an other thing, this is not "colorPicker.input" but "colorPicker.oninput".

Then I just setting the background color with the value of the color picker.