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

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.